0

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
4
  • 2
    You have to escape the \- in the string you pass to new RegExp as \\-. Otherwise, put the - at the end of the character set. Commented Sep 21, 2015 at 3:48
  • @torazaburo: Beginning, not end. Edit: Hey, interesting, both work. Useful to know. At least one rex engine I used (not JavaScript) took - at the end to mean no upper bound on the character class. Commented Sep 21, 2015 at 3:49
  • @T.J.Crowder beginning or end? Commented Sep 21, 2015 at 3:51
  • @torazaburo: Yup, apparently. Commented Sep 21, 2015 at 3:52

1 Answer 1

5

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.