笔记:substring和substr的区别

substring和substr的区别

两者都是截取字符串。

相同点:如果只是写一个参数,两者的作用都一样:都是是截取字符串从当前下标以后直到字符串最后的字符串片段。

substr(startIndex);

substring(startIndex);

例:

var str = '123456789';
console.log(str.substr(2));    //  "3456789"
console.log(str.substring(2)) ;//  "3456789"

不同点:第二个参数

substr(startIndex,lenth): 第二个参数是截取字符串的长度(从起始点截取某个长度的字符串);

substring(startIndex, endIndex): 第二个参数是截取字符串最终的下标 (截取2个位置之间的字符串,‘含头不含尾’)。

例:

console.log("123456789".substr(2,5));    //  "34567"
console.log("123456789".substring(2,5)) ;//  "345"

String.substr(startIndex,lenth) 这个是我们常用的从指定的位置(startIndex)截取指定长度(lenth)的字符串; String.substring(startIndex, endIndex) 这个是startIndex,endIndex里找出一个较小的值,然后从字符串的开始位置算起,截取较小值位置和较大值位置之间的字符串,截取出来的字符串的长度为较大值与较小值之间的差。

参考:

http://blog.csdn.net/adley_function/article/details/52130762 https://zhidao.baidu.com/question/1367343929337374859.html

猜你喜欢

转载自blog.csdn.net/qq_39108466/article/details/78581081