Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  141] [ 5]  / answers: 1 / hits: 27874  / 9 Years ago, tue, august 4, 2015, 12:00:00

So I have this code where I'd like to replace all single backslashes with 2 backslashes, for example: ---> \ I tried to do this by the following code:



string = string.replace(new RegExp(\, g), \\);


But apparently this doesn't work because I get the following error:




Uncaught SyntaxError: Invalid regular expression: //: at end of pattern




Any idea why?


More From » regex

 Answers
32

The is a escape character for regular expressions, and also for javascript strings. This means that the javascript string \ will produce the following content :. But that single is a escape character for the regex, and when the regex compiler finds it, he thinks: nice, i have to escape the next character... but, there is no next character. So the correct regex pattern should be \. That, when escaped in a javascript script is \\.



So you should use:



string = string.replace(new RegExp(\\, g), \\); 


as an alternative, and to avoid the javascript string escape, you can use a literal regex:



string = string.replace(/\/g, \\);

[#65540] Sunday, August 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brandensebastiand

Total Points: 323
Total Questions: 115
Total Answers: 106

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;