前言
正则表达式是前端开发中不可或缺的一部分,它可以帮助我们处理字符串中的各种格式,例如验证邮箱、匹配 URL、提取文本等等。在 ES12 标准下,JavaScript 正则表达式新增了两个功能:regexp 执行器和 regexp 切换,本文将详细介绍这两个功能的使用方法以及其学习和指导意义。
regexp 执行器
在 ES12 标准下,JavaScript 正则表达式新增了一个执行器(executor)的方法,可以通过该方法直接执行正则表达式,而不需要使用 exec
或 test
方法。该方法的语法如下:
/正则表达式/方法名(字符串)
其中,方法名可以是 match
、replace
、search
或 split
,这些方法都可以接受一个正则表达式作为参数。下面分别介绍这四个方法的使用方法。
match 方法
match
方法可以将字符串中符合正则表达式的部分提取出来,返回一个数组。如果正则表达式中有分组,则返回的数组中会包含每个分组的匹配结果。如果没有匹配结果,则返回 null
。
示例代码:
const str = 'hello world'; const result = /hello (\w+)/.match(str); console.log(result); // ["hello world", "world"]
replace 方法
replace
方法可以将字符串中符合正则表达式的部分替换成指定的内容,并返回替换后的字符串。如果正则表达式中有分组,则可以在替换内容中使用 $1
、$2
等来引用分组的匹配结果。
示例代码:
const str = 'hello world'; const result = str.replace(/hello (\w+)/, 'hi $1'); console.log(result); // "hi world"
search 方法
search
方法可以在字符串中查找符合正则表达式的部分,并返回第一个匹配结果的位置。如果没有匹配结果,则返回 -1
。
示例代码:
const str = 'hello world'; const result = str.search(/world/); console.log(result); // 6
split 方法
split
方法可以将字符串按照正则表达式的匹配结果进行分割,并返回一个数组。
示例代码:
const str = 'hello,world'; const result = str.split(/,/); console.log(result); // ["hello", "world"]
regexp 切换
在 ES12 标准下,JavaScript 正则表达式新增了一个切换(toggle)的方法,可以在正则表达式中切换某些标志的开关。该方法的语法如下:
/正则表达式/.toggle(标志)
其中,标志可以是 g
、i
、m
或 s
,分别表示全局匹配、忽略大小写、多行匹配和点匹配任意字符。下面分别介绍这四个标志的使用方法。
g 标志
g
标志表示全局匹配,即匹配所有符合正则表达式的部分。如果不加 g
标志,则只匹配第一个符合条件的部分。
示例代码:
const str = 'hello world'; const regexp = /l/; console.log(regexp.test(str)); // true console.log(regexp.test(str)); // true console.log(regexp.toggle('g').test(str)); // true console.log(regexp.test(str)); // false
i 标志
i
标志表示忽略大小写,即不区分大小写地匹配字符串。如果不加 i
标志,则区分大小写。
示例代码:
const str = 'Hello World'; const regexp = /hello/; console.log(regexp.test(str)); // false console.log(regexp.toggle('i').test(str)); // true
m 标志
m
标志表示多行匹配,即可以匹配多行的字符串。如果不加 m
标志,则只匹配单行的字符串。
示例代码:
const str = 'hello\nworld'; const regexp = /^world/; console.log(regexp.test(str)); // false console.log(regexp.toggle('m').test(str)); // true
s 标志
s
标志表示点匹配任意字符,即可以匹配换行符等特殊字符。如果不加 s
标志,则点不能匹配特殊字符。
示例代码:
const str = 'hello\nworld'; const regexp = /world./; console.log(regexp.test(str)); // false console.log(regexp.toggle('s').test(str)); // true
结语
通过本文的介绍,我们了解了 ES12 标准下 JavaScript 正则表达式的两个新功能:regexp 执行器和 regexp 切换。这两个功能可以让我们更方便地处理字符串中的各种格式,提高开发效率。同时,我们也应该注意正则表达式的性能和安全性,避免出现不必要的问题。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/679688d9504e4ea9bdd523f7