有关js正则的方法

714 阅读3分钟

RegExp

  • test

  • exec

    test() 方法执行一个检索,用来查看正则表达式与指定的字符串是否匹配。返回 truefalse

var str = 'hello world!';
var result = /^hello/.test(str);
console.log(result); // true

当正则表达式设置了全局标志g ,那么test 方法的调用是有副作用的,即改变正则表达式的lastIndex 属性的值,再次调用则会在lastIndex 处开始匹配字符串。(相同的特性也表现在exec方法上)

exec() 方法在一个指定字符串中执行一个搜索匹配。返回一个结果数组或null

var reg = /he(ll)o/g;
var result1 = reg.exec('hello world hello juejin')
var result2 = reg.exec('hello world hello juejin')
console.log(result1)
// ["hello", "ll", index: 0, input: "hello world hello juejin", groups: undefined]
console.log(result2)
//["hello", "ll", index: 12, input: "hello world hello juejin", groups: undefined]

如果匹配成功,exec() 方法返回一个数组(包含额外的属性index 和 input 并更新正则表达式对象的lastIndex属性。完全匹配成功的文本将作为返回数组的第一项,从第二项起,后续每项都对应正则表达式内捕获括号里匹配成功的文本。如果匹配失败,exec() 方法返回null 并将lastIndex 重置为 0 。

String

  • match

  • matchAll

  • replace

    math() 方法当匹配非全局模式的正则时返回内容和上述的exec() 类似,如果匹配全局模式的正则时

var reg1 = /world|juejin/;
var result1 = 'hello world hello juejin'.match(reg1);
console.log(result1);
// ["world", index: 6, input: "hello world hello juejin", groups: undefined]
var reg2 = /world|juejin/g;
var result2 = 'hello world hello juejin'.match(reg);
console.log(result2);
// ["world", "juejin"]

mathAll() 方法必须接受全局模式的正则表达式,它返回值一个包含所有匹配正则表达式的结果及分组捕获组的迭代器

var reg = /world|juejin/g;
var result = 'hello world hello juejin'.matchAll(reg);
console.log([...result]); 
// [ 
//   ["world", index: 6, input: "hello world hello juejin", groups: undefined], 
//   ["juejin", index: 18, input: "hello world hello juejin", groups: undefined]
// ]

replace() 方法返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern是字符串,则仅替换第一个匹配项。

原字符串不会改变。

var result = 'hello world hello juejin'.replace(/(he)(ll)o/g, (...args) => {
 console.log(args)
 // 此处打印两次
 // ["world", "he", "ll", 0, "hello world hello juejin"]
 // ["hello", "he", "ll", 12, "hello world hello juejin"]
 return 'xxx'
})
// result "xxx world xxx juejin"
匹配规则表达式
除了换行符之外的任何字符.
单个数字, [0-9]\d
除了[0-9]\D
包括下划线在内的单个字符,[A-Za-z0-9_]\w
非单字字符\W
匹配空白字符,包括空格、制表符、换页符和换行符\s
匹配非空白字符\S

匹配规则元字符
0次或1次?
0次或无数次*
1次或无数次+
特定次数{x}, {min,max}

边界和标志表达式
单词边界\b
字符串开头
字符串结尾$
多行模式m
大小写忽略模式i
全局模式g