开发学院

您的位置:首页>教程>正文

教程正文

ES6 String对象方法substr()

ES6 String对象方法substr()

  此方法通过指定的字符数返回在指定位置开始的字符串中的字符。

语法

string.substr(start[, length]);

参数详情

  • start −开始提取字符的位置(介于0和1之间的整数小于字符串的长度)。

  • length − 要提取的字符数

返回值

  substr()方法返回截取后的字符串

例子

var str = "Apples are round, and apples are juicy."; 
console.log("(1,2): "    + str.substr(1,2)); 
console.log("(-2,2): "   + str.substr(-2,2)); 
console.log("(1): "      + str.substr(1)); 
console.log("(-20, 2): " + str.substr(-20,2)); 
console.log("(20, 2): "  + str.substr(20,2));

 

输出

(1,2): pp 
(-2,2): y. 
(1): pples are round, and apples are juicy. 
(-20, 2): nd 
(20, 2): d