Reputation: 25
Test string is "page-42440233_45778105" pattern "(page-\d+_\d+)"
Online tester(http://www.regexr.com/) successfuly finded mathc,but in browser js result is null. Why?
var re = new RegExp("(page-\d+_\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
Upvotes: 0
Views: 63
Reputation: 77778
I think this would be a better pattern
var re = /^page-\d+_\d+$/i;
It also matches the beginning (^
) and end ($
) of the string
message.match(re);
//=> ["page-42440233_45778105"]
Upvotes: 1
Reputation: 369034
You need to escape \
if you use string literal:
var message = "page-42440233_45778105";
var re = new RegExp("(page-\\d+_\\d+)", "gim");
var r_array = message.match(re);
console.log(r_array);
// => ["page-42440233_45778105"]
More preferably, use regular expression literal:
var re = /(page-\d+_\d+)/gim;
Upvotes: 0
Reputation: 382112
When you use a string literal, you must escape the \
:
var re = new RegExp("(page-\\d+_\\d+)", "gim");
A better solution here would be to use a regex literal :
var re = /(page-\d+_\d+)/gim
Don't use the RegExp constructor if the regular expression is constant, regex literals are much more convenient.
Upvotes: 0