File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -766,3 +766,37 @@ for (const match of string.matchAll(regex)) {
766
766
Array .from (string .matchAll (regex))
767
767
```
768
768
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
+
You can’t perform that action at this time.
0 commit comments