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

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

    Quotemeta isn't implemented natively as far as I know, but I've used this a few months ago for just this:

    function quotemeta (str) {
      // http://kevin.vanzonneveld.net
      // +   original by: Paulo Freitas
      // *     example 1: quotemeta(". + * ? ^ ( $ )");
      // *     returns 1: '\. \+ \* \? \^ \( \$ \)'
      return (str + '').replace(/([\.\\\+\*\?\[\^\]\$\(\)])/g, '\\$1');
    }
    

    From http://phpjs.org/functions/quotemeta:496

提交回复
热议问题