Please, look into this code. Why does creating of the same regular expression by different ways (by /regex/ literal and through RegExp constructor) cause different result? Why doesn't the second pattern match the whitespace in the str?
var str = " ";
var pat1 = /\s/;
document.writeln(pat1.test(str)); // shows "true"
var pat2 = new RegExp("\s");
document.writeln(pat2.test(str)); // shows "false"
Can't find the answer on my question anywhere. Thanks
Please, look into this code. Why does creating of the same regular expression by different ways (by /regex/ literal and through RegExp constructor) cause different result? Why doesn't the second pattern match the whitespace in the str?
var str = " ";
var pat1 = /\s/;
document.writeln(pat1.test(str)); // shows "true"
var pat2 = new RegExp("\s");
document.writeln(pat2.test(str)); // shows "false"
Can't find the answer on my question anywhere. Thanks
Share Improve this question asked Aug 11, 2011 at 14:53 AndrewAndrew 631 gold badge1 silver badge3 bronze badges1 Answer
Reset to default 19You need to escape the backslash since it's in a string:
var pat2 = new RegExp("\\s");