stephenhuh stephenhuh - 6 months ago 19
Javascript Question

RegExp Object Literal notation vs Constructor notation difference

var digits = "B2";
var re = new RegExp("/\d+/");
console.log(/\d+/.test(digits));
console.log("digits matches to :", digits.match(re));


why does digits.match(re) return NULL whereas the .test returns true?
When I just run digits.match("/\d+/"); I get the correct answer.

Answer

The new RegExp() syntax doesn't use forward slashes / as the delimiter. It's assumed that the entire string is the regex. Also, backslashes must be escaped, since this is a requirement of strings when you aren't referencing an escape character.

These are the same:

digits.match(new RegExp("\\d+")); // 2

digits.match(/\d+/); // 2