天天看点

js字符串提取substring() substr() - Kaiqisanjs字符串提取substring() substr()总结

js字符串提取substring() substr()

観客のみんなさんこんにちは、Kaiqisanです, 之前讲解了数组的截取,虽然在本质上字符串是一个成员为一个个字符的数组,但是两者并不相通,字符串也是无法使用数组的一些方法的。所以今天来特地讲讲字符串专属的截取方法。

substring(start, end)

: 该方法用于提取字符串中介于两个指定下标之间的字符(不包含end下标的那个字符)。第二个参数end为可选项,如果第二个参数没有填写的话,字符串截取操作就会从第一个参数下标开始一直截取到最后一个参数。与 slice()和 substr()方法不同的是,substring() 不接受负的参数。

这个方法有一个返回值,需要参数接受,为字符串。

let str = "Hello world and you"
console.log(str.substring(3)) // "lo world and you"
           
let str = "Hello world and you"
console.log(str.substring(3, 7)) // "lo w" // 截取下标为3,4,5,6这四位字符
           

substr()

: 该方法可在字符串中抽取从 start 下标开始的指定数目的字符。如果第二个参数过大,则会截取到最后一个字符为止,不报错。第一个参数接受负数作为参数,表示从倒数第n个下标开始截取。

这个方法有一个返回值,需要参数接受,为字符串。

let str = "Hello world and you"
console.log(str.substr(3, 7)) // "lo worl" // 刚好7位
           
let str = "Hello world and you"
console.log(str.substr(3, 20)) 
// "lo world and you" 第二个“希望截取的位数”如果过大,会一直截到最后一位就直接结束
           
let str = "Hello world and you"
console.log(str.substr(-3, 2)) // yo 从倒数第三位开始截取也表示从下标为(str.length - 3)处开始截取
           

总结

这俩方法对应了数组截取操作的splice和slice,原理来说都是一样的,作用也是一样的,但是这两两方法无法“串味”,数组无法使用substring() 方法和substr()方法,字符串无法使用splice()方法.

继续阅读