238

I need to escape the regular expression special characters using java script.How can i achieve this?Any help should be appreciated.


Thanks for your quick reply.But i need to escape all the special characters of regular expression.I have try by this code,But i can't achieve the result.

RegExp.escape=function(str)
            {
                if (!arguments.callee.sRE) {
                    var specials = [
                        '/', '.', '*', '+', '?', '|',
                        '(', ')', '[', ']', '{', '}', '\\'
                    ];
                    arguments.callee.sRE = new RegExp(
                    '(\\' + specials.join('|\\') + ')', 'gim'
                );
                }
                return str.replace(arguments.callee.sRE, '\\$1');

            }

function regExpFind() {
            <%--var regex = new RegExp("\\[munees\\]","gim");--%>
                    var regex= new RegExp(RegExp.escape("[Munees]waran"));
                    <%--var regex=RegExp.escape`enter code here`("[Munees]waran");--%>
                    alert("Reg : "+regex);
                }

What i am wrong with this code?Please guide me.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • 1
    I have added an answer here [ https://stackoverflow.com/a/63838890/5979634 ] which implemented the proposed standardized method despite TC39's unfortunate decision. Even if they don't see the value to standardize it, we all likely will if we can all use the same one. – Drewry Pope Sep 13 '20 at 10:18

3 Answers3

571

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

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

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
  • 1
    What's special on ','? Just curious. – Viliam May 20 '13 at 14:10
  • 1
    @Viliam I don’t know the exact details, but IIRC the `,` needs to be escaped for backwards compatibility with some old/buggy JavaScript engines. – Mathias Bynens May 20 '13 at 18:36
  • 8
    I get complaints from regex validators when I don't escape forward slashes, so I added that to your most excellent pattern `/[-[\]{}()*+?.,\\/^$|#\s]/g` – 2Toad Apr 11 '15 at 16:37
  • @MathiasBynens Thanks a ton, very handy when the regex is dynamic and we're using a constructor. – Bharat May 25 '16 at 15:26
  • My attempt at converting the ES speck: `replace(/[\^$\\.*+?()[\]{}|]/g, '\\$&')` – Jared Christensen Jun 06 '16 at 18:58
  • Tnx!, it's great answer. I just add this before yours `.replace(..)` line: `if (!text || typeof text != "string") { return ''; }` for handling a null or not string input or even an empty string, it's more efficient. – Dudi Aug 31 '17 at 14:09
  • golden! did the job when querying over block cipher encrypted data – Dan Ochiana Oct 05 '17 at 20:39
  • 14
    The [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) also have a suggested function (search for function escapeRegExp) using `string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')`. Anyone familiar with potential shortcomings with it? – John McMahon Nov 20 '18 at 20:50
  • `#`? Out of curiosity, could anyone explain why this character is present in the answer? In a quick search, I couldn't find any notion it has (or had planned to get) any special meaning in any regexp flafour. (@MathiasBynens ?) – myf Oct 02 '19 at 09:41
  • Do not use the provided solution! It messes up strings with `$` character! – Nowaker Jun 18 '20 at 00:06
  • 2
    I have added an answer here [ https://stackoverflow.com/a/63838890/5979634 ] which implemented the proposed standardized method despite TC39's unfortunate decision. Even if they don't see the value to standardize it, we all likely will if we can all use the same one. – Drewry Pope Sep 13 '20 at 10:17
  • Anyone getting double \\ instead of \ after replacing ? – MMilanov Dec 11 '22 at 08:56
19

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

Ben Rowe
  • 28,406
  • 6
  • 55
  • 75
  • double blackslash is worked for me, thanks – yussan Dec 21 '18 at 07:47
  • @Ben Rowe Can you please suggest a regex for word like US$ with boundary? I've tried "\b(US\$)\b" but does not seem to work well – Jeetendra Ahuja Jan 16 '19 at 20:55
  • 1
    @JeetendraAhuja - The "$" character is not a word character, so "\b(US\$)\b" would only match if the following character is a word character. You're probably looking for "\b(US\$)\B" to signify that the last one is _not_ a word boundary. – Trondster Apr 23 '20 at 13:47
  • if using variable with `RegExp`, the ``\`` need to escape to ``\\``, for example if you want to replace `(a)` in `(a)bc` to empty and get `bc`, it could be written as `var regex = new RegExp('\\\(a\\\)' ,"g"); str = str.replace(regex, '');` – yu yang Jian Jan 25 '21 at 15:54
10

With \ you escape special characters

Escapes special characters to literal and literal characters to special.

E.g: /\(s\)/ matches '(s)' while /(\s)/ matches any whitespace and captures the match.

Source: http://www.javascriptkit.com/javatutors/redev2.shtml

Ivaylo Slavov
  • 8,839
  • 12
  • 65
  • 108
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155