Skip to content

JS 中正则相关方法 ​

JS 中正则相关的方法共 7 个,字符串的方法有:search、split、replace 和 match。

正则的方法有:test 和 exec。

容易混淆的实际就两种情况,一种是 replace() 方法的替换函数,参数为匹配项、各分组、匹配项索引和原始字符串,另一种是返回数组的方法,在有 g 标志时,结果数组里都是匹配项,而没有 g 标志时,结果数组会额外有 groups、index 和 input 属性分别保存各分组、匹配项索引和原始字符串。

search(regexp) 在字符串中搜索与正则匹配的内容,返回第一个匹配项的索引位置。

  • regexp:正则表达式参数,如果传入非正则,会隐式转换为正则表达式。不支持全局搜索(即不能使用 g 标志)。
js
const str = 'abc'
str.search('c') // 2
str.search(/c/) // 2

String#split ​

split(separator, [limit]) 使用指定的分隔符将字符串进行分割,返回一个字符串数组。

  • separator:分隔符,可以是字符串或正则。
  • limit:非负整数,限制返回数组的最大长度。
js
const str = '2022.10.25'
str.split('.') // [2022, 10, 25]

String#replace ​

replace(pattern, replacement) 在字符串中匹配指定模式并替换为新内容,返回新的字符串。

  • pattern:要替换的模式,可以是字符串或正则,字符串则只能匹配到第一项,正则可用 g 标志进行全局替换。
  • replacement:要替换的内容,可以是字符串或函数。如果是函数,则第一个参数为成功匹配的值,剩下参数为各个捕获的分组,倒数第二个参数为匹配值的索引,倒数第一个参数为原字符串。函数的返回的值将会替换掉匹配项。

另有 replaceAll() 方法,会进行全局替换。

js
const str = '2022.10.25'

str.replace(/\./g, '-') // 2022-10-25

// 使用捕获分组
str.replace(/(\w+)\.(\w+)\.(\w+)/, "$1-$2-$3") // 2022-10-25

// 使用函数作为替换参数
str.replace(/(\w+)\.(\w+)\.(\w+)/, function(match, group1, group2, group3, index, input) {
  // ['2022.10.25', '2022', '10', '25', 0, '2022.10.25']
  console.log(match, group1, group2, group3, index, input) 
  return `${group1}-${group2}-${group3}`
})

String#match ​

match(regexp) 在字符串中搜索与正则匹配的内容,返回字符串数组或 null。

  • regexp:正则表达式参数,如果传入非正则,会隐式转换为正则表达式。如果没有 g 标志则结果数组只包含第一个匹配的字符串,数组会有 index、input 和 groups 属性,分别表示匹配项的索引、原始字符串、命名分组对象。如果加 g 标志,则返回的数组中会包含所有匹配的字符串,但不会有 index 等属性。
js
const str = '2022.10.25'

str.match('\\.')  // ['.', index: 4, input: '2022.10.25', groups: undefined]
str.match(/\./g) // ['.', '.']

另有 matchAll() 方法可进行全局匹配,注意返回的是一个迭代器。

注意 search 和 match 方法都会将传入的非正则隐式转换为正则表达式,所以需要转义,如 '.' 需要写成 '\\.'。

RegExp#test ​

test(str) 测试字符串中是否存在正则匹配的内容,返回布尔值。

  • str:要测试的字符串。

当正则带有全局标志 g 时,test() 方法会记录 lastIndex。

js
const regex = /abc/

regex.test('a') // true
regex.test('d') // false

RegExp#exec ​

exec(str) 在字符串中执行正则搜索,返回包含匹配项的字符串数组或 null。

  • str:要搜索的字符串。

无 g 标志时,总是从索引 0 处开始搜索,总匹配第一个,lastIndex 会始终为 0。有 g 标志时,一般会用循环来处理,会从 lastIndex 开始搜索,依次返回每个匹配项,lastIndex 会自动更新,遍历完后会重置为 0。

js
const str = '2022.10.25'
const regex = /\./g
let match
while((match = regex.exec(str)) !== null) {
  console.log(match, regex.lastIndex)
}

// ['.', index: 4, input: '2022.10.25', groups: undefined] 5
// ['.', index: 7, input: '2022.10.25', groups: undefined] 8