JS提供三个截取字符串的方法,分别是:
- slice()
- substring()
- substr()
它们都可以接受一个或两个参数。
1.slice()方法
let a = 'rcinn.cn'
a.slice(3)
console.log(a) // 输出结果为'nn.cn'
当输入一个参数的时候,字符串.slice(n) 表示截取从索引值为n开始(包括索引值n)到字符串结束的子字符串
let a = 'rcinn.cn'
a.slice(2,4)
console.log(a) // 输出结果为'in'
字符串.slice(x,y)表示截取从索引值为x开始(包括索引值x)到索引值为y(不包括索引值为y的字符)的子字符串。
let a = 'rcinn.cn'
a.slice(-1)
console.log(a) // 输出结果为'n'
a.slice(-2)
console.log(a) // 输出结果为'cn'
字符串从后往前索引的时候,最后一个字符的索引值为-1,a.slice(-1)表示截取最后一个字符串,a.slice(-2)表示从倒数第二个字符串开始截取,一直到字符串结束的子字符串。
2.substring()的用法和slice()的用法基本相同
3.substr()方法
let a = 'rcinn.cn'
a.substr(3)
console.log(a) // 输出结果为'nn.cn'
当输入一个参数的时候,字符串.substr(n) 表示截取从索引值为n开始(包括索引值n)到字符串结束的子字符串
let a = 'rcinn.cn'
a.substr(-1)
console.log(a) // 输出结果为'n'
a.substr(-2)
console.log(a) // 输出结果为'cn'
字符串从后往前索引的时候,最后一个字符的索引值为-1,a.substr(-1)表示截取最后一个字符串,a.substr(-2)表示从倒数第二个字符串开始截取,一直到字符串结束的子字符串。
substr()当有两个参数的时候和slice()和substring()的方法就不相同了
let a = 'rcinn.cn'
a.substr(2,4)
console.log(a) // 输出结果为'inn.'
字符串.substr(x,y) 表示截取从索引值为x开始(包括索引值x)截取y个字符串,y的含义表示截取的字符串的个数!!