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?
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, "\\\\");
You escaped the backslash for JavaScript's string literal purposes, but you did not escape it for the regex engine's purposes. Remember, you are dealing with layers of technology here.
So:
string = string.replace(new RegExp("\\\\", "g"), "\\\\");
Or, much better:
string = string.replace(/\\/g, "\\\\");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With