Javascript equivalent of Perl's \Q … \E or quotemeta()

后端 未结 3 1215
小蘑菇
小蘑菇 2020-12-05 05:29

In Perl regular expressions, you can surround a subexpression with \\Q and \\E to indicate that you want that subexpression to be matched as a lite

3条回答
  •  抹茶落季
    2020-12-05 05:51

    There's also a quotemeta npm module, which you can use in node.js or in the browser. The implementation is to quote all non-word characters, (short for [^a-zA-Z0-9_]).

    String(str).replace(/(\W)/g, '\\$1');
    

    This works because all the characters that need escaping are non-words, while the other characters that end getting escape are harmless. For example, here the percent character gets escaped, but it still matches normally in the RegExp, although it didn't need to be escaped:

    if ("Hello%".match(RegExp(String("%").replace(/(\W)/g,'\\$1')))) { console.log("matched!"); } 
    

    ```

    Someone has forked the quotemeta module and noted that the capturing parens aren't needed, so the regex can be further simplified like this:

    String(str).replace(/\W/g, '\\$&');
    

提交回复
热议问题