js字符串的方法合集

一、charAt()&charCodeAt()

charAt()返回给定位置的字符,charCodeAt()返回给定位置的字符编码。

let str = 'pjhpwjldh'
console.log(str.charAt(2)) //h
console.log(str.charCodeAt(2))  //104

二、slice()&substr()&substring()

这三个方法都用于截取字符串,不会改变原字符串,返回截取的字符串,他们的区别在于:
slice()接收一或两个参数,指明截取的开始及结束位置,当参数为负数时,相当于负数加上字符串长度的位置,当第二个参数小于第一个参数时,返回空字符串

let str = 'pjhpwjldh'
let newstr = str.slice(1,-5)  
console.log(newstr)  //jhp

substring()与slice()不同的地方在于当参数为负数时,会默认转换为0,并将较小的参数作为开始位置

let str = 'pjhpwjldh'
let newstr = str.substring(1,-5)  
console.log(newstr)  //p

substr()第一个参数为开始的位置,第二个参数为截取的个数,当第一个参数为负数时,相当于负数加上字符串长度的位置,当第二个参数为负数时,会返回空字符串

let str = 'pjhpwjldh'
let newstr = str.substr(1,-5)  
console.log(newstr)  //''

三、trim()

trim()会返回新的字符串,删除前置和后缀的所有空格,不改变原字符串

let str = '   pjh  pwjld  h    '
let newstr = str.trim()
console.log(newstr)  //pjh  pwjld  h

四、toUpperCase()&toLowerCase()

let str = 'pjhpwjldh'
let newstr = str.toUpperCase()
console.log(newstr)  //PJHPWJLDH

版权声明:本文为weixin_43206959原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。