javascript字符串罕用api应用汇总(二)

本文讲述所有能应用正则的字符串api

  • search
  • replace
  • replaceAll
  • split
  • match

search 按正则搜寻字符串

这个api应用很简略,就是搜寻字符串中合乎规定的字符的结尾索引

  const rex = /\w+/  const str = 'abc123321'  console.log(str.search(rex)) // 3

当然也是能够用字符串搜寻的,字符串只能搜寻固定的,正则能够规定类型,天然是比拟弱小的

replace、replaceAll 字符串按规定替换

  const rex = /\w+/  const str = 'abc123321'  console.log(str.replace(rex, '这是数字替换后的内容')) // abc这是数字替换后的内容  // replaceAll应用须要留神的是,因为replaceAll是全局替换的,故rex须要加上全局修饰符  const rex2 = /\w+/g  const str2 = 'abc123ccb223'  console.log(str2.replaceAll(rex2, '555')) // abc555ccb555

这两个办法我在后面文章有介绍过比拟具体的用法,感兴趣的能够去看看一文搞懂String的replace用法

split、match 按规定把字符串宰割

split是将字符串宰割成数组

  const str = 'a,b,c,d,e,f,g'  // 依照特定字符宰割字符串  conosle.log(str.split(',')) // ['a', 'b', 'c', 'd', 'e', 'f', 'g']  const str2 = 'a23b4213c5433d213'  // 依照特定规定宰割字符串  console.log(str.split(/\d+/)) // ['a', 'b', 'c', 'd', '']

match则跟split办法相同,是将按规定匹配的字符串分成数组

  const str2 = 'a23b4213c5433d213'  // !留神 须要多个的肯定要加全局修饰符  console.log(str2.match(/\d+/g)) // ['23', '4213', '5433', '213']  console.log(str2.match(/\d+/)) // ['23', index: 1, input: 'a23b4213c5433d213', groups: undefined]

如果没有全局修饰符就会在数组上加几个属性index匹配的字符在原字符串的地位,input原字符串,groups在正则设置的组成员,
这里演示一下捕捉组

  const str1 = '16px'  const str2 = '16rem'  const str3 = '16rpx'  const rex = /(?<num>[0-9]+)(?<unit>[a-z]+)/  console.log(str1.match(rex).groups) // { num: '16', unit: 'px' }  console.log(str2.match(rex).groups) // { num: '16', unit: 'rem' }  console.log(str3.match(rex).groups) // { num: '16', unit: 'rpx' }  // 这就是match办法的捕捉组的根本用法