mtpultz
mtpultz

Reputation: 18268

JavaScript RegExp from a string then running .test() doesn't seem to work

I thought that by instantiating a pattern = new RegExp() and passing a string then using .test(value) would be the same as using /^...$/.test(value), but they don't appear to be equal as using RegExp and passing a string fails each time. Is this not correct? On MDN it seems to say that this should work.

SHOULD ALL FAIL AND THEY DO

var str = "7D>";
var res = /^[A-Za-z0-9\d=!\-@._*]*$/.test(str);
console.log(res); // false which is correct

var patt = /^[A-Za-z0-9\d=!\-@._*]*$/;
var res = patt.test(str);
console.log(res); // false which is correct

var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");
var res = patt.test(str);
console.log(res); // false which is correct, but suspicious based on follow results

SHOULD ALL PASS AND THEY DON'T

var str = "7D";
var res = /^[A-Za-z0-9\d=!\-@._*]*$/.test(str);
console.log(res); // true which is correct

var patt = /^[A-Za-z0-9\d=!\-@._*]*$/;
var res = patt.test(str);
console.log(res); // true which is correct

BUT BOTH THESE ATTEMPTS FAIL WHEN THEY SHOULD PASS

var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");
var res = patt.test(str);
console.log(res); // false which is NOT correct

var patt = new RegExp("^[A-Za-z0-9\d=!\-@._*]*$");
var res = patt.test(str);
console.log(res); // ALSO false which is NOT correct

Upvotes: 0

Views: 59

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Two things:

  1. You don't include the / when using a string

  2. You do have to escape backslashes (as always, in a string literal)

So this:

var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");

should be

var patt = new RegExp("^[A-Za-z0-9\\d=!\\-@._*]*$");
//                    ^           ^^   ^^        ^

If you had flags, you'd include them as a second string argument:

var patt = new RegExp("^[a-z\\d=!\\-@._*]*$", "i");

Side note:

\d means "digit" which is defined in the spec as 0-9, so having 0-9 and \d in the character class is redundant

Upvotes: 5

Related Questions