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

2
  • 1
    re1 = new RegExp('^(\\d+)_SAMPLE_PROJECT$','gi') Commented Dec 9, 2015 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). Commented Dec 9, 2015 at 16:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In a way, 'except when it does': \n is newline, so is regexp-from-string \\n

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.