Ferus
Ferus

Reputation: 1118

Getting "error: invalid regular expression"

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?

Upvotes: 13

Views: 32263

Answers (2)

CaldasGSM
CaldasGSM

Reputation: 3062

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, "\\\\");

Upvotes: 18

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

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, "\\\\");

Upvotes: 5

Related Questions