字符串的方法(共16项)

1、length

  查询字符串的长度

  var str = 'hello world' console.log(str.length) // 结果为: 11 

2、indexOf()

  查询字符串中指定文本首次出现时的索引

  var str = 'hello world' console.log(str.indexOf('h')) // 结果为: 0 

3、lastIndexOf()

  查询字符串中指定文本最后一次出现的索引

  var str = 'hello world' console.log(str.lastIndexOf('o')) // 结果为: 7 

  注:当 indexOf 与 lastIndexOf 查找的文本不存在时,则返回值为 -1

    可添加第二个参数:表 开始查询的起始位置

4、search()

  var str = 'hello world' console.log(str.search('o')) // 结果为: 4 

  注:search 与 indexOf 查找文本结果是相同的,不同点在于

  • search() 不支持传递第二个参数(即,无法自定义设置开始查找的起始位置)
  • indexOf() 不支持设置更复杂的搜索条件(比如:正则)

5、slice()

  提取字符串中的指定文本,返回值为提取出来的文本内容

  var str = 'hello world' console.log(str.slice(1,4)) // 结果为: ell 

  注:共两个参数,默认从左至右依次查询,当参数值为负数时,则从右至左依次查询,第一个参数表示提取开始位置,截止位置为第二个参数的前一位

    当仅传递一个参数时,则提取直到文本结束位置

6、substring()

  var str = 'hello world' console.log(str.substring(1)) // 结果为: ello world 

  注:不同于 slice() 的地方在于: substring() 参数传递不支持负数

7、substr()

  var str = 'hello world' console.log(str.substr(1,4)) // 结果为: ello 

  注:类似与 slice() ,不同点在于:substr() 第二个参数为截取的长度

8、replace()

  指定替换字符串中的文本,返回值为替换后的新数组

  var str = 'hello world' console.log(str.replace('o','a')) // 结果为: hella world 

  注:默认仅更换首个指定文本,可使用正则进行全局替换

  var str = 'hello world' console.log(str.replace(/o/g,'a')) // 结果为: hella warld 

9、toUpperCase()

  将字符串转成大写

  var str = 'hello world' console.log(str.toUpperCase()) // 结果为: HELLO WORLD 

10、toLowerCase()

  将字符串转成小写

11、concat()

  连接字符串

  var str = 'hello world' console.log(str.concat(' ','kcy')) // 结果为: hello world kcy 

12、trim()

  删除字符串两旁的空格

  var str = ' hello world ' console.log(str.trim()) // 结果为: hello world 

13、charAt()

  根据索引查找相应文本

  var str = 'hello world' console.log(str.charAt(0)) // 结果为: h 

14、split()

  通过指定符号(参数),将字符串转换成相应的数组

  var str = 'hello,world' console.log(str.split('')) // 结果为: ['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd'] 

  注:传递参数,则按指定参数对字符串分隔转换成相应数组,如果传递参数为 '' 则对字符串进行拆分,返回单个字符的数组

15、match()

  根据传递的参数,在字符串内匹配相应内容,并以数组的形式返回

  var str = 'hello world' console.log(str.match(/orl/g)) // 结果为: ['orl'] 

16、includes()

  根据传递的参数,判断是否存在字符串内,返回值为布尔值

  var str = 'hello world' console.log(str.includes('o')) // 结果为: true 

posted on 2021-11-26 13:39  二两余晖  阅读(220)  评论(0编辑  收藏  举报