How to escape regular expression special characters using javascript? [duplicate]
Asked Answered
C

3

246

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.

Cynical answered 25/6, 2010 at 2:21 Comment(1)
I have added an answer here [ https://mcmap.net/q/21318/-is-there-a-regexp-escape-function-in-javascript ] 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.Impertinence
C
587

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.

Chiu answered 16/2, 2012 at 11:48 Comment(13)
What's special on ','? Just curious.Systematology
@Systematology I don’t know the exact details, but IIRC the , needs to be escaped for backwards compatibility with some old/buggy JavaScript engines.Chiu
I get complaints from regex validators when I don't escape forward slashes, so I added that to your most excellent pattern /[-[\]{}()*+?.,\\/^$|#\s]/gHelli
@MathiasBynens Thanks a ton, very handy when the regex is dynamic and we're using a constructor.Weakling
My attempt at converting the ES speck: replace(/[\^$\\.*+?()[\]{}|]/g, '\\$&')Macassar
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.Biisk
golden! did the job when querying over block cipher encrypted dataBlacktail
The MDN Docs also have a suggested function (search for function escapeRegExp) using string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'). Anyone familiar with potential shortcomings with it?Antalkali
#? 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 ?)Cowley
Do not use the provided solution! It messes up strings with $ character!Rebecarebecca
I have added an answer here [ https://mcmap.net/q/21318/-is-there-a-regexp-escape-function-in-javascript ] 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.Impertinence
Anyone getting double \\ instead of \ after replacing ?Clearcole
The proposal has just advanced to stage 2 🥳Malebranche
I
21

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

Indicatory answered 25/6, 2010 at 2:23 Comment(4)
double blackslash is worked for me, thanksFusiform
@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 wellConyers
@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.Numeral
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, '');Lp
J
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

Jackfish answered 25/6, 2010 at 2:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.