Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Possible Duplicate:
Is there a RegExp.escape function in Javascript?

I am trying to build a javascript regex based on user input:

function FindString(input) {
    var reg = new RegExp('' + input + '');
    // [snip] perform search
}

But the regex will not work correctly when the user input contains a ? or * because they are interpreted as regex specials. In fact, if the user puts an unbalanced ( or [ in their string, the regex isn't even valid.

What is the javascript function to correctly escape all special characters for use in regex?

share|improve this question

marked as duplicate by George Stocker Aug 30 '12 at 0:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7  
Lodash have an escapeRegExp dedicated function: lodash.com/docs#escapeRegExp – Yves M. Mar 6 '16 at 14:38

Short 'n Sweet

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());
share|improve this answer
13  
Wow, that's verbose. I prefer bobince's version. But anything that works without escaping things unnecessarily... – T.J. Crowder Jun 15 '12 at 15:50
2  
I expect all of the characters that SHOULD be escaped, not just the ones that MUST be escaped, which is what linters such as JSLint undersand. – CoolAJ86 Oct 6 '12 at 17:37
5  
Why is it replaced by '\\$&'. What is that suppose to mean? I am sorry, I am JS newbie. – Sushant Gupta Jan 13 '14 at 15:38
4  
@SushantGupta The "\\" adds the new backslash which escapes the matched special regex character. The "$&" is a back-reference to the contents of the current pattern match, adding the original special regex character. – danhbear Jan 14 '14 at 5:07
4  
Most of these characters don't need to be escaped within a character class. Dash and forward slash don't need to be escaped at all. So, this can be simplified as: return str.replace(/[[{}()*+?^$|\]\.\\]/g, "\\$&"); – richardtallent Sep 9 '15 at 20:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.