4

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?

cluster1
  • 4,968
  • 6
  • 32
  • 49
  • Because `/\/` is an invalid regular expression. If you want a regex to match a single backslash, you'll need either `/\\/` or `new RegExp('\\\\')` – Phil Jul 05 '16 at 06:34

4 Answers4

6

\ 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 \.

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
5

The string literal '\\' creates a string containing nothing but a single backslash character, because within string literals the backslash is an escape character.

A single backslash character is not a valid regular expression.

If you want a regex that matches a single backslash then that needs to be escaped within the regex, so you need to do either:

re = /\\/;
// or
re = new RegExp('\\\\');
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
3

I believe the reason you are getting this error is that the effective regex which you are feeding into the JavaScript engine is a single backslash \.

The reason for this is that the first backslash escapes the second one. So you are putting in a literal backslash, which doesn't make any sense.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    You're right. " var test1 = '\'; " The backslash escapes the second apostrophe. So the string has no ending sign and is invalid. Something like that can't exist. Shortest possible string consisting of nothing but a backslash would be " var test2 = '\\' " . Therefore a RegExp searching for test1 would make no sense. Thanks for the help. You gave the correct input. – cluster1 Jul 05 '16 at 07:00
0

The backslash \ is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash. \ (backslash) followed by any of [\^$. ?*+(){} escapes the special character to suppress its special meaning.

Gopal Yadav
  • 368
  • 2
  • 8