ES6 正则表达式的新特性解析
在 ES6 中,正则表达式得到了许多新特性的支持,大大加强了正则表达式在前端开发中的应用。本文将为大家一一解析这些新特性,并提供示例代码。
- 点匹配所有字符
在 ES5 中,使用点符号 . 可以匹配除了换行符以外的任意字符。而在 ES6 中,新增了 s 标记,可以匹配所有字符,包括换行符。例如:
const str = "hello\nworld"; console.log(str.match(/hello.world/)); // null console.log(str.match(/hello.world/s)); // hello\nworld
- 使用模板字符串作为正则表达式
在 ES6 中,我们可以使用模板字符串来构建正则表达式,这样可以更方便的进行拼接。例如:
const name = "Tom"; console.log("hello, my name is " + name); // hello, my name is Tom console.log(`hello, my name is ${name}`); // hello, my name is Tom const reg = new RegExp(`${name} is a good boy`); console.log(reg.test("Tom is a good boy")); //true
- 简化写法
ES6 增加了许多简化写法,使得我们可以更方便的书写正则表达式。
(1) y 标记:表示粘连匹配,即从上一次匹配成功的位置开始匹配。例如:
const str = "aaaaa"; const reg = /a/y; //可以和直接写成 /a/g 一样表示全局匹配 console.log(reg.exec(str)); // "a" console.log(reg.exec(str)); // "a" console.log(reg.exec(str)); // "a" console.log(reg.exec(str)); // "a" console.log(reg.exec(str)); // "a" console.log(reg.exec(str)); // null
(2) u 标记:表示 Unicode 匹配。例如:
const str = "\uD842\uDFB7"; console.log(/^.$/.test(str)); // false console.log(/^.$/u.test(str)); // true
(3) i 标记:表示不区分大小写匹配。例如:
const str = "hello world"; console.log(str.match(/hello/)); // ["hello"] console.log(str.match(/HELLO/i)); // ["hello"]
(4) g 标记:表示全局匹配。例如:
const str = "hello, hello, world"; console.log(str.match(/hello/g)); // ["hello", "hello"]
- 命名捕获组
在 ES6 中,我们可以使用命名捕获组来更加方便的获取到匹配到的内容。例如:
const str = "hello world"; const reg = /(?<name>hello) (?<age>\w+)/; const result = str.match(reg); console.log(result.groups.name); // "hello" console.log(result.groups.age); // "world"
以上就是 ES6 正则表达式的新特性的解析,希望对前端开发者在日常开发中使用正则表达式有所启发。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67b8d21e306f20b3a66dacfc