241

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.

1
  • 1
    I have added an answer here [ 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. Sep 13, 2020 at 10:18

3 Answers 3

576

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/tc39/proposal-regex-escaping

Update: The abovementioned proposal was rejected (but there is a 2023 rewrite in progress), so keep implementing this yourself for now.

13
  • 1
    What's special on ','? Just curious.
    – Viliam
    May 20, 2013 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. May 20, 2013 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, 2015 at 16:37
  • 14
    The MDN Docs also have a suggested function (search for function escapeRegExp) using string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'). Anyone familiar with potential shortcomings with it? Nov 20, 2018 at 20:50
  • 2
    I have added an answer here [ 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. Sep 13, 2020 at 10:17
21

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

4
  • double blackslash is worked for me, thanks
    – yussan
    Dec 21, 2018 at 7: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 Jan 16, 2019 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, 2020 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, ''); Jan 25, 2021 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

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