The code I use at the moment is ugly because I have to write "replace" separately for every special character.
var str = ":''>";
str.replace("'","\\'").replace(">","\\>");
I would like to prepend backslash to < > * ( ) and ? through regex.
The code I use at the moment is ugly because I have to write "replace" separately for every special character.
var str = ":''>";
str.replace("'","\\'").replace(">","\\>");
I would like to prepend backslash to < > * ( ) and ? through regex.
Using a regex that matches the characters with a character set, you could try:
str = str.replace(/([<>*()?])/g, "\\$1");
DEMO: http://jsfiddle.net/8ar3Z/
It matches any of the characters inside of the [ ]
(the ones you specified), captures them with the surrounding ()
(so that it can be referenced as $1
in the replaced text part), and then prepends with \\
.
UPDATE:
As a suggestion from Mr. @T.J.Crowder, it is unnecessary to capture with ()
, changing $1
to $&
, written as:
str = str.replace(/[<>*()?]/g, "\\$&");
DEMO: http://jsfiddle.net/8ar3Z/1/
References: