-2

Regex is returning false for format '(###) ###-####', this regex works fine online with regex testers but not in javascript.

let phoneNumberRegex = new RegExp('^\(\d{3}\)\s\d{3}-\d{4}$');
if (phoneNumberRegex.test(phoneNumberElement.value)) {
   ...
}

Number that is failing is (123) 456-7890, I would like this exact format of number.

Airo
  • 70
  • 13

1 Answers1

1

Backslashes need to be escaped with another backslash in string literals. To avoid this, use a regular expression literal instead of the RegExp constructor.

let phoneNumberRegex = /^\(\d{3}\)\s\d{3}-\d{4}$/;
console.log(phoneNumberRegex.test('(123) 456-7890'));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80