我目前使用的代码很难看,因为我必须为每个特殊字符单独写"替换".
var str = ":''>";
str.replace("'","\\'").replace(">","\\>");
Run Code Online (Sandbox Code Playgroud)
我想将反斜杠添加到<>*()和?通过正则表达式.
使用与字符集匹配的正则表达式,您可以尝试:
str = str.replace(/([<>*()?])/g, "\\$1");
Run Code Online (Sandbox Code Playgroud)
演示: 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, "\\$&");
Run Code Online (Sandbox Code Playgroud)
DEMO: http://jsfiddle.net/8ar3Z/1/
References:
$1 and $& use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter