Skip to content

Commit 4a46f9f

Browse files
committed
docs(regex): add RegExp.escape()
1 parent 74bc512 commit 4a46f9f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

docs/regex.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -766,3 +766,37 @@ for (const match of string.matchAll(regex)) {
766766
Array.from(string.matchAll(regex))
767767
```
768768

769+
## RegExp.escape()
770+
771+
ES2025 添加了 RegExp.escape() 方法,它用来对字符串转义,使其可以安全地用于正则表达式。
772+
773+
```javascript
774+
RegExp.escape('(*)')
775+
// '\\(\\*\\)'
776+
```
777+
778+
上面示例中,原始字符串的三个字符`(``*``)`在正则表达式都有特殊含义,RegExp.escape() 可以对它们进行转义。
779+
780+
注意,转义以后,每个特殊字符之前都加上了两个反斜杠。这是因为当该字符串用于正则表达式,字符串的转义机制会将两个反斜杠先转义成一个反斜杆,即`\\(`变成`\(`,从而正好用于正则表达式。
781+
782+
没有特殊含义的字符,不会被转义。
783+
784+
```javascript
785+
RegExp.escape('_abc123')
786+
// '_abc123'
787+
```
788+
789+
该方法的经典用途是搜索和替换文本。
790+
791+
```javascript
792+
function replacePlainText(str, searchText, replace) {
793+
const searchRegExp = new RegExp(
794+
RegExp.escape(searchText),
795+
'gu'
796+
);
797+
return str.replace(searchRegExp, replace)
798+
}
799+
```
800+
801+
上面示例中,RegExp.escape() 先对用户输入的关键词进行转义,然后就可以将其当作正则表达式处理。
802+

0 commit comments

Comments
 (0)