2

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));

​See the above code sample. reg1 and reg2 are same regular expressions, but why the test results are different? I test it in Chrome. Here's the online demo: http://jsfiddle.net/DzfWC/

Community
  • 1
  • 1
Mouhong Lin
  • 4,402
  • 4
  • 33
  • 48

1 Answers1

4

When you use it as a literal string you must escape every \ with \\:

var reg1 = new RegExp('^http:\\/\\/abc\\.com\\/\\d+$');
some
  • 48,070
  • 14
  • 77
  • 93