0

I have a regex expression which i use for email address validation. It is working fine as literal expression but showing different result when using the RegExp constructor.

var emailpattern=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;

console.log(emailpattern.test('nithin@gmail.com'))//true

var obj = new RegExp('^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$','g');

console.log(obj.test('nithin@gmail.com'))//false
Beingnin
  • 2,288
  • 1
  • 21
  • 37
  • flagged as duplicate? If i knew it has to be double escaped i would not ask this question at the first place. – Beingnin Jul 06 '18 at 11:34

1 Answers1

1

You need to remove quotes for the pattern which you have specified in the new RegExp() to get rid of extra overhead of escaping the \ character:

var emailpattern=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;

console.log(emailpattern.test('nithin@gmail.com'))//true

var obj = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,'g');

console.log(obj.test('nithin@gmail.com'))//false

Escaping the \ character:

var emailpattern=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;

console.log(emailpattern.test('nithin@gmail.com'))//true

var obj = new RegExp('(([^<>()\\[\\]\\\.,;:\s@"]+(\\.[^<>()\\[\\]\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))','g');

console.log(obj.test('nithin@gmail.com'))//false
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62