描述
此方法用于返回字符串的必需子字符串。它接受一个整数值,指示子字符串的起始值和字符串的长度,并返回所需的子字符串。如果起始值为负,则substr()方法将其用作字符串末尾的字符索引。
用法
下面给出的是substr()JavaScript 的方法。我们可以在 CoffeeScript 代码中使用相同的方法。
string.substr(start[, length])
示例
下面的例子演示了使用substr()CoffeeScript 代码中的 JavaScript 方法。将此代码保存在具有名称的文件中string_substr.coffee
str = "Apples are round, and apples are juicy.";
console.log "The sub string having start and length as (1,2) is:" + str.substr 1,2
console.log "The sub string having start and length as (-2,2) is:" + str.substr -2,2
console.log "The sub string having start and length as (1) is:" + str.substr 1
console.log "The sub string having start and length as (-20, 2) is:" + str.substr -20,2
console.log "The sub string having start and length as (20, 2) is:" + str.substr 20,2;
打开command prompt并编译 .coffee 文件,如下所示。
c:\> coffee -c coffee string_substr.coffee
在编译时,它会为您提供以下 JavaScript。
// Generated by CoffeeScript 1.10.0
(function() {
var str;
str = "Apples are round, and apples are juicy.";
console.log("The sub string having start and length as (1,2) is:" + str.substr(1, 2));
console.log("The sub string having start and length as (-2,2) is:" + str.substr(-2, 2));
console.log("The sub string having start and length as (1) is:" + str.substr(1));
console.log("The sub string having start and length as (-20, 2) is:" + str.substr(-20, 2));
console.log("The sub string having start and length as (20, 2) is:" + str.substr(20, 2));
}).call(this);
现在,打开command prompt再次运行 CoffeeScript 文件,如下所示。
c:\> coffee string_substr.coffee
在执行时,CoffeeScript 文件产生以下输出。
The sub string having start and length as (1,2) is:pp The sub string having start and length as (-2,2) is:y. The sub string having start and length as (1) is:pples are round, and apples are juicy. The sub string having start and length as (-20, 2) is:nd The sub string having start and length as (20, 2) is:d
相关用法
- CoffeeScript String slice()用法及代码示例
- CoffeeScript String split()用法及代码示例
- CoffeeScript String search()用法及代码示例
- CoffeeScript String toUpperCase()用法及代码示例
- CoffeeScript String toLocaleUpperCase()用法及代码示例
- CoffeeScript String concat()用法及代码示例
- CoffeeScript String match()用法及代码示例
- CoffeeScript String lastIndexOf()用法及代码示例
- CoffeeScript String toLowerCase()用法及代码示例
- CoffeeScript String charAt()用法及代码示例
- CoffeeScript String localeCompare()用法及代码示例
- CoffeeScript String toLocaleLowerCase()用法及代码示例
- CoffeeScript String indexOf()用法及代码示例
- CoffeeScript String charCodeAt()用法及代码示例
- CoffeeScript Date setHours()用法及代码示例
- CoffeeScript Date setUTCFullYear()用法及代码示例
- CoffeeScript Date getDay()用法及代码示例
- CoffeeScript Date getDate()用法及代码示例
- CoffeeScript Date getYear()用法及代码示例
- CoffeeScript Math pow()用法及代码示例
注:本文由纯净天空筛选整理自 CoffeeScript String - substr()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。