-1

I can't understand when I need one and two backward slashes \.

First, see an example:

const rxHttps = new RegExp("\/");
console.log(rxHttps.test("/")); // true

const rxQuestion = new RegExp("\\?");
console.log(rxQuestion.test("?")); // true

const rxAnotherQuestion = new RegExp("\?"); // Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat

In the above example, to use a character /, it needs just one \.

However, ? needs two \, or SyntaxError occurs.

This is really confusing. I can't make heads or tails of it.

Why are they different? Am I misunderstanding?

Yonggoo Noh
  • 1,811
  • 3
  • 22
  • 37

1 Answers1

0

because '?' is used to mean that what's before it can or not exist like {0,}

for example

var reg = new RegExp('a?');
// this has the same meaning as using
// var reg = new RegExp('a\?');
reg.test('a'); // will display true
reg.test('anything'); // this will also display true
reg.test('123'); // this also displays true

so if you want to check of the existence of '?' character, you have to escape it, and since it's used as '\?' also, then you have to escape it using '\?'

Why does it give you syntax error ? because it's expecting something to check if it exists or not and you're not giving it anything.

Abed Murrar
  • 91
  • 1
  • 9