字符串操作方法(slice、substr、substring)
相同点:1、都接收1-2个参数,且参数值为正的时候,返回的新字符串都一样,不改变原始值
不同点:1、当接收1个参数为负数时,如
let str = 'hello world';
console.log(str.slice(-3)); // ‘rld’ //字符串长度+负参数值 相当于str.slice(8)
console.log(str.substr(-3)) //'rld' //原理同slice()
console.log(str.substring(-3)) // 'hello world' //相当于(substring(0))
2、当接收2个参数,且有负数时,如
let str = 'hello world';
console.log(str.slice(3,-4)); //'lo w'; 相当于str.slice(3,7)
console.log(str.substr(3,-4)); // '空串'; //因为第二个参数如为负数,则为0,且相当于返回一个长度为0的字符串
console.log(str.substring(3,-4)); // 'hel' //相当于str.substring(3,0)其实也是str.substring(0,3)