2

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
  • 58,320
  • 7
  • 77
  • 95

1 Answers1

9

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
  • 233,700
  • 52
  • 457
  • 497