字符串slice,substr和substring的区别

276 阅读1分钟

1.他们都接收两个参数,slice和substring接收的是起始位置和结束位置(不包括结束位置),而substr接收的则是起始位置和所要返回的字符串长度。另外,substring是以两个参数中较小一个作为起始位置,较大的参数作为结束位置。

var test = 'hello world';
console.log(test.slice(4,7));             //o w
console.log(test.substring(4,7));         //o w
console.log(test.substr(4,7));            //o world

console.log(test.slice(7,4));             //空字符串
console.log(test.substring(74));        //o w

2.当接收的参数是负数时,slice会将它字符串的长度与对应的负数相加,结果作为参数;substr则仅仅是将第一个参数与字符串长度相加后的结果作为第一个参数;substring则干脆将负参数都直接转换为0。

var test = 'hello world';

console.log(test.slice(-3));         //rld
console.log(test.substring(-3));     //hello world
console.log(test.substr(-3));        //rld

console.log(test.slice(3,-4));       //lo w
console.log(test.substring(3,-4));   //hel
console.log(test.substr(3,-4));      //空字符串