Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match whitespace in Javascript regexp by object, created through RegExp constructor

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

like image 678
Andrew Avatar asked Aug 11 '11 14:08

Andrew


1 Answers

You need to escape the backslash since it's in a string:

var pat2 = new RegExp("\\s");
like image 106
Sean Bright Avatar answered Oct 20 '22 18:10

Sean Bright