-2

I have been staring at these two flavors of same regex and can't figure out why the outcome is different:

var projectName="SAMPLE_PROJECT",
fileName="1234_SAMPLE_PROJECT",
re1 = new RegExp('^(\d+)_SAMPLE_PROJECT$','gi'),
re2 = /^(\d+)_SAMPLE_PROJECT$/gi,
matches1 = re1.exec(fileName),
matches2 = re2.exec(fileName);

console.log(matches1);//returns null
console.log(matches2);//returns correctly

Here is the jsbin : https://jsbin.com/badoqokumu/edit?html,js,output

Any idea what I must be doing wrong with instantiating RegExp?

Thanks.

Deewendra Shrestha
  • 2,313
  • 1
  • 23
  • 53
  • 1
    `re1 = new RegExp('^(\\d+)_SAMPLE_PROJECT$','gi')` – anubhava Dec 09 '15 at 16:06
  • Stages of backslash\\plague: `raw (cured) \ `, `string parse \\ `, `string double parse \\\\ `, `string triple parse \\\\\\\\ `. Always be sure to use the right level depending on how many string parsers your text is going through. Also, suggest making a macro for +/- stages in your editor. That and never write a PHP string that writes a JS string that is then turned into JS regex. That's one of the very few things that suffers from stage three Backslash\\\\\\\\Plague. We don't speak of stage four (washed through eval() as well, for example). – abluejelly Dec 09 '15 at 16:15

1 Answers1

1

In the first case, you have a string literal, which uses \ to introduce escape sequences. \d in a string is just d. If you want \d, you need to type \\d instead.

In the second case, you have a regular expression literal, which does not interpret \ as a string escape sequence.

jcaron
  • 17,302
  • 6
  • 32
  • 46