slice、substring、substr的区别

var a='hello world';
var b='hello world';
var c='hello world';
var A=a.substr(3,1);
var B=b.substring(3,5);
var C=c.slice(3,5);
console.log('a:'+a+'
'+'b:'+b+'
'+'c:'+c);
console.log(A+'
'+B+'
'+C);

//输出
a:hello world
b:hello world
c:hello world
A:l
B:lo
C:lo

结论

slicesubstringsubstr都是用来截取字符串的函数。返回一个新的字符串。而且都对原字符串没有影响。

slicesubstring的用法相同,接收两个参数,第一个参数是从第几位开始截取(包含此位),第二个参数是截取到第几位(不包含此位)。

substr也接受两个参数,第一个参数是从第几位截取(包含此位),第二个参数是截取几位字符串。

原文地址:https://www.cnblogs.com/zhaozhipeng/p/8080750.html