使用正则表达式为所选字符添加反斜杠

Pin*_*nky 2 javascript regex

我目前使用的代码很难看,因为我必须为每个特殊字符单独写"替换".

var str = ":''>";
str.replace("'","\\'").replace(">","\\>");
Run Code Online (Sandbox Code Playgroud)

我想将反斜杠添加到<>*()和?通过正则表达式.

Ian*_*Ian 7

使用与字符集匹配的正则表达式,您可以尝试:

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(事实上,我是你的第一个upvote!),但你不需要一个捕获组:`str = str.replace(/ [<>*()?]/g,"\\ $&") ;` (2认同)