substr()
优质
小牛编辑
135浏览
2023-12-01
描述 (Description)
此方法用于返回字符串的必需子字符串。 它接受一个整数值,表示子字符串的起始值和字符串的长度,并返回所需的子字符串。 如果起始值为负,则substr()方法将其用作字符串末尾的字符索引。
语法 (Syntax)
下面给出了JavaScript的substr()方法的语法。 我们可以在CoffeeScript代码中使用相同的方法。
string.substr(start[, length])
例子 (Example)
以下示例演示了CoffeeScript代码中JavaScript的substr()方法的用法。 将此代码保存在名为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