js字符串处理的几种方法总结
前端开发中,字符串处理是比较常见的,笔者在最近复习的过程中也把它整理了出来。
首先,先来看看js截取三姐妹substring()、subsstr()、slice()
1、slice(start, end)
大姐slice()、从start开始,到end结束,开始的位置从0不是1,不包括end,支持数组分割,支持负数,返回数组
let test = 'hello world!'
console.log(test.length)
console.log(test.slice(1, 9))
console.log(test.slice(6))
console.log(test.slice(9, 1))
console.log(test.slice(-2))
console.log(test.slice(0, -2))
console.log(test.slice(-4, -2))
console.log(test.slice(-2, 4))
总结
①第一个参数比第二个参数大,结果返回空字符串
②传入参数是负数,slice()会先做运算 test.length + 负数参数。
2、substr(start, length)
二姐substr()、从