通过对象匹配 Javascript regexp 中的空格,通过 RegExp 构造函数创建
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7028045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Match whitespace in Javascript regexp by object, created through RegExp constructor
提问by Andrew
Please, look into this code. Why does creating of the same regular expression by different ways (by /regex/literal and through RegExpconstructor) cause different result? Why doesn't the second pattern match the whitespace in the str?
请看一下这段代码。为什么通过不同的方式(通过/ regex/literal 和通过RegExp构造函数)创建相同的正则表达式会导致不同的结果?为什么第二个模式与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
无法在任何地方找到我的问题的答案。谢谢
回答by Sean Bright
You need to escape the backslash since it's in a string:
您需要转义反斜杠,因为它在字符串中:
var pat2 = new RegExp("\s");