Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 347
Ferus Avatar asked Aug 04 '15 16:08

Ferus


2 Answers

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, "\\\\");
like image 85
CaldasGSM Avatar answered Nov 12 '22 11:11

CaldasGSM


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, "\\\\");
like image 4
Lightness Races in Orbit Avatar answered Nov 12 '22 12:11

Lightness Races in Orbit