Possible Duplicate:
Why RegExp with global flag in Javascript give wrong results?
var reg1 = new RegExp('^http:\/\/abc\.com\/\d+$');
var reg2 = /^http:\/\/abc\.com\/\d+$/;
var url = 'http://abc.com/1657706754';
// expected: true, actual: false
document.write(reg1.test(url));
document.write('<br/>');
// expected: true, actual: true
document.write(reg2.test(url));
请参阅上面的代码示例。 reg1
和reg2
是相同的正则表达式,但为什么 test
结果不同?我在 Chrome 中测试了它。这是在线演示:http://jsfiddle.net/DzfWC/
最佳答案
当您将其用作文字字符串时,您必须使用 \\
对每个 \
进行转义:
var reg1 = new RegExp('^http:\\/\\/abc\\.com\\/\\d+$');
关于javascript - javascript RegExp : same regular expressions produce different result 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12367471/