字符串的切割方法有三种分别是str.slice() str.substring() str.substr()
slice()、substr()和substring()的第一个参数即时开始切割的位置,这里要注意的是字符串的下标是由0开始的,这些方法如果只传第一个参数,则表示从第一个参数的位置开始取到字符串的结束位置例如:
let str='hello world'
str.slice(6) //world
str.slice(-3)//rld str.length //11 -3+11=8 所以可以表示为str.slice(8)
str.slice(-3,-1)// str.slice(8,10) //rl
str.substr(7) //orld
str.substring(0) //hello world
如果这些方法都传第二个参数那么区别是:
str.slice(2,4) //ll 顾头不顾尾
str.substring(2,4)//ll 顾头不顾尾
str.substr(2,6)//llo wo 注意这个地方不一样了他的第二个参数不是索引位置了而是从第一个参数开始取6个字符
字符串的基本方法:
var str='hello world'
str.charAt(1) //e
str.charCodeAt(1) //101 字符编码
str.concat('bin') //hello worldbin
str.concat('a','bin') //hello worldabin
str.indexOf('o') // 4
str.indexOf('o',6) //7 从第6个索引开始往后找O
str.lastIndexOf('0') //7
str.lastIndexOf('0',6)//4 //从第6个索引开始往前找o
var str=' aaa '
str.trim() //aaa 清除字符串的前后空格而且不影响str原来的值
str.toLowerCase() //hello world
str.toLocaleLowerCase() //hello world 一般用于特定地域
str.toUpperCase()//HELLO WORLD
str.toLocaleUpperCase()//HELLO WORLD 一般用于特定地域