Design & Download
Your JS Library
in Seconds!!!

Snippet: quoteRegExp() - Escaping RegExp Metacharacters

Written by Christopher West (cwest) on November 16, 2015.
Turn any string into a regular expression that matches the exact string without worrying about encoding the metacharacters yourself.
function quoteRegExp(str, opt_flagsOrMakeRegExp) {
  var ret = str.replace(/[[\](){}.+*^$|\\?-]/g, '\\$&');
  return opt_flagsOrMakeRegExp === '' || opt_flagsOrMakeRegExp
    ? new RegExp(ret, opt_flagsOrMakeRegExp == true ? '' : opt_flagsOrMakeRegExp)
    : ret;
}

quoteRegExp(...) API Documentation

Turn any string into a regular expression that matches the exact string without worrying about encoding the metacharacters yourself.

Parameters

  1. str {string}:
    The string that should be modified so that any characters that would normally serve as metacharacters in a regular expression will be escaped.
  2. flagsOrMakeRegExp {string|boolean}:
    Optional. If not specified or if false, it will cause just the escaped version of str to be returned. If true, it will be as if the empty string was passed in. A string represents the flags to be set in the returned regular expression.

Returns

If true, a regular expression without flags will be returned. If this is a non-empty string, a regular expression with the specified characters representing the corresponding flags will be returned. In all other cases just the escaped string that can be used as a regular expression will be returned.

Example

Thanks to this snippet, you can now turn any string into a regular expression that matches the exact string without worrying about encoding the metacharacters yourself:

console.log(YourJS.quoteRegExp('1+2^3=9' true));
// -> /1\+2\^3=9/