views:

47

answers:

3

Hi to all,

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

A: 

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

Ben Rowe
+2  A: 

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.

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

Claudio Redi
A: 

Hi Redi & BEn,

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.

Muneeswaran Balasubramanian