js 基础:字符串常用方法

186 阅读1分钟

1.charAt 方法:用于输入第n位的字符。 使用方法:str.charAt(索引值)

    var a='abcdefg'
    console.log(a.charAt(0)) // 'a'

2.charCodeAt 方法:用于返回第n位的Unicode编码。 使用方法:str.charCodeAt(索引值)

    console.log(a.charCodeAt(0)) // 97

3.indexOf 方法:返回某个字符对应的索引值,没找到返回-1。 使用方法:str.indexOf(某个字符)

    console.log(a.indexOf('bc')) // 1
    console.log(a.indexOf('bcdg')) // -1

4.lastIndexOf 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索,没找到返回-1。 使用方法:str.lastIndexOf(某个字符)

   console.log(a.lastIndexOf('bcdg'))  // -1
   console.log('abbb'.lastIndexOf('b'))  // 3

5.substring 方法:用于截取字符串,截取时,包含前边的索引对应的字符,不包含后边索引对应的字符 使用方法:str.substring(开始的索引,结束的索引(不包含))

   console.log(a.substring(2,3)) // 'c'

6.substr 方法:用于截取字符串,截取从第n位开始,一共截取m位。 使用方法:str.substr(从哪开始截取,截取几位)

    console.log(a.substr(3,1)) // 'd'

7.toLowerCase方法:用于把大写字母转成小写 使用方法: str.toLowerCase()

    var c='HELLO'
    console.log(c.toLowerCase()) // 'hello'

8.toUpperCase 方法:用于把小写字母转成大写

   var d='hello'
   console.log(d.toUpperCase()) //'HELLO'

9.split 方法:用于字符串转成数组 使用方法: str.split(作为断开标记的字符)

  var e='hello'
  console.log(e.split('')) // ['h', 'e', 'l', 'l', 'o']

10.trim 方法用于删除字符串的头尾空白符,空白符包括:空格、制表符 tab、换行符等其他空白符等。

 var f=' abc d '
 console.log(f.trim()) // 'abc d'