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

后端 未结 3 1218
小蘑菇
小蘑菇 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:56

    There is no such built-in feature.

    Rather than implementing your own, I advise you look into the multitude of regex escape functions available on the internet.

    That page proposes the following solution (by Colin Snover):

    RegExp.escape = function(text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    }
    

    or advises to use the XRegExp library.

提交回复
热议问题