Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegExp : Why causes a double backslash ( \\ ) an error? [duplicate]

Have found this out by accident and have no idea what's the reason.

// Results in "Syntax error in regular Expression".
var re = RegExp('\\');

I know that the constructor-function expects a string as parameter. And that the backslash is used within strings to escape characters with special meaning. I know that I have to escape characters like \d to \\d .

So therefore: The right backslash should the interpreted as some normal character.

Instead it throws an error. Why?

Can anyone explain this to me?

like image 788
cluster1 Avatar asked Oct 30 '25 12:10

cluster1


1 Answers

\ is used to escape \ in strings, so to get \d as you wrote you need to do \\d.

Also in regexp you need to escape \ with \\.

So you have two escape syntaxes that need to take place in regexps, using a single \\ will mean \ in regexp which is not correct, because it needs to be escaped.

So to workaround this you need double escape: \\\\ - this will be a regex looking for \.

like image 83
Krzysztof Krasoń Avatar answered Nov 01 '25 02:11

Krzysztof Krasoń



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!