How to escape regular expression special characters using javascript?

JavascriptRegex

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

Solution 3 - Javascript

With </code> 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMuneeswaran BalasubramanianView Question on Stackoverflow
Solution 1 - JavascriptMathias BynensView Answer on Stackoverflow
Solution 2 - JavascriptBen RoweView Answer on Stackoverflow
Solution 3 - JavascriptClaudio RediView Answer on Stackoverflow