最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Match whitespace in Javascript regexp by object, created through RegExp constructor - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 19

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

var pat2 = new RegExp("\\s");

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论