Is there a RegExp.escape function in Javascript?

I just want to create a regular expression out of any possible string.

var usersString = "Hello?!*`~World()[]";
var expression = new RegExp(RegExp.escape(usersString))
var matches = "Hello".match(expression);

Is there a built in method for that? If not, what do people use? Ruby has RegExp.escape . I don't feel like I'd need to write my own, there's gotta be something standard out there. Thanks!


The function linked above is insufficient. It fails to escape ^ or $ (start and end of string), or - , which in a character group is used for ranges.

Use this function:

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

While it may seem unnecessary at first glance, escaping - (as well as ^ ) makes the function suitable for escaping characters to be inserted into a character class as well as the body of the regex.

Escaping / makes the function suitable for escaping characters to be used in a JS regex literal for later eval.

As there is no downside to escaping either of them it makes sense to escape to cover wider use cases.

And yes, it is a disappointing failing that this is not part of standard JavaScript.


For anyone using lodash, since v3.0.0 a _.escapeRegExp function is built-in:

_.escapeRegExp('[lodash](https://lodash.com/)');
// → '[lodash](https://lodash.com/)'

And, in the event that you don't want to require the full lodash library, you may require just that function!


Most of the expressions here solve single specific use cases.

That's okay, but I prefer an "always works" approach.

function regExpEscape(literal_string) {
    return literal_string.replace(/[-[]{}()*+!<=:?./^$|#s,]/g, '$&');
}

This will "fully escape" a literal string for any of the following uses in regular expressions:

  • Insertion in a regular expression. Eg new RegExp(regExpEscape(str))
  • Insertion in a character class. Eg new RegExp('[' + regExpEscape(str) + ']')
  • Insertion in integer count specifier. Eg new RegExp('x{1,' + regExpEscape(str) + '}')
  • Execution in non-JavaScript regular expression engines.
  • Special Characters Covered:

  • - : Creates a character range in a character class.
  • [ / ] : Starts / ends a character class.
  • { / } : Starts / ends a numeration specifier.
  • ( / ) : Starts / ends a group.
  • * / + / ? : Specifies repetition type.
  • . : Matches any character.
  • : Escapes characters, and starts entities.
  • ^ : Specifies start of matching zone, and negates matching in a character class.
  • $ : Specifies end of matching zone.
  • | : Specifies alternation.
  • # : Specifies comment in free spacing mode.
  • s : Ignored in free spacing mode.
  • , : Separates values in numeration specifier.
  • / : Starts or ends expression.
  • : : Completes special group types, and part of Perl-style character classes.
  • ! : Negates zero-width group.
  • < / = : Part of zero-width group specifications.
  • Notes:

  • / is not strictly necessary in any flavor of regular expression. However, it protects in case someone (shudder) does eval("/" + pattern + "/"); .
  • , ensures that if the string is meant to be an integer in the numerical specifier, it will properly cause a RegExp compiling error instead of silently compiling wrong.
  • # , and s do not need to be escaped in JavaScript, but do in many other flavors. They are escaped here in case the regular expression will later be passed to another program.

  • If you also need to future-proof the regular expression against potential additions to the JavaScript regex engine capabilities, I recommend using the more paranoid:

    function regExpEscapeFuture(literal_string) {
        return literal_string.replace(/[^A-Za-z0-9_]/g, '$&');
    }
    

    This function escapes every character except those explicitly guaranteed not be used for syntax in future regular expression flavors.


    For the truly sanitation-keen, consider this edge case:

    var s = '';
    new RegExp('(choice1|choice2|' + regExpEscape(s) + ')');
    

    This should compile fine in JavaScript, but will not in some other flavors. If intending to pass to another flavor, the null case of s === '' should be independently checked, like so:

    var s = '';
    new RegExp('(choice1|choice2' + (s ? '|' + regExpEscape(s) : '') + ')');
    
    链接地址: http://www.djcxy.com/p/74014.html

    上一篇: 如何检查一个字符串“StartsWith”是否是另一个字符串?

    下一篇: Javascript中有RegExp.escape函数吗?