CodingNoob123
CodingNoob123

Reputation: 153

RegExp.test returns false even though it should be true

I'm trying to write this simple code into chrome live test and can't get it to return true.

var regExS = new RegExp("\d+x\d+");
regExS.test(" 240x120 (399.00)");

Even if I change the value to "240x120" it returns false. I've been googling and looking around and can't solve it.

Upvotes: 0

Views: 372

Answers (2)

pawel
pawel

Reputation: 36965

The result of var regExS = new RegExp("\d+x\d+"); is /d+xd+/.
You need to escape the backslashes when building a regex from a string:

var regExS = new RegExp("\\d+x\\d+");

or you could use a regex literal

var regExS = /\d+x\d+/;

Upvotes: 1

Phil Ross
Phil Ross

Reputation: 26090

If you are creating a RegExp from a string, the backslashes will need to be escaped ("\d" is the same as "d"):

var regExS = new RegExp("\\d+x\\d+");

Alternatively you can use a regular expression literal:

var regExS = /\d+x\d+/;

Upvotes: 1

Related Questions