1

I was answering a question, and the following returns false

var regexp = new RegExp("([\w\.-]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})");
var result = regexp.test( $("#email").val() ); // returns false

While

var regexp = /([\w\.-]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/;
var result = regexp.test( $("#email").val() ); // returns true

Why is that??

Amit Joki
  • 56,285
  • 7
  • 72
  • 91

1 Answers1

8

You need to escape \ when you use RegExp constructor function.

new RegExp("([\\w\\.-]+)@((?:[\\w]+\\.)+)([a-zA-Z]{2,4})");

Quoting from MDN's RegExp constructor Docs,

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

var re = /\w+/;
var re = new RegExp("\\w+");
Community
  • 1
  • 1
thefourtheye
  • 221,210
  • 51
  • 432
  • 478