1

I just need to know why the dollar sign is needed at the end of the regex for validating US phone numbers

function telephoneCheck(str) {

return (/^(1)?(\s)?(\(\d{3}\)|\d{3})[\s-]?\d{3}[\s-]?\d{4}$/).test(str) 

}
console.log(telephoneCheck("551-555-5555"));

1 Answers1

2

^ is start of string and $ is end of string.

Therefore we want to match only this string, not a substring within a larger string.

Fully explained:

  • ^ assert the start of the string
  • (1)? zero or one "1"
  • (\s)? zero or one whitespace character
  • (\(\d{3}\)|\d{3}) 3 digits in () or 3 digits
  • [\s-]? zero or one whitespace or "-"
  • \d{3} 3 digits
  • [\s-]?zero or one whitespace or "-"
  • \d{4} 4 digits
  • $ end of string

On regex101

  • With:

enter image description here

  • Without:

enter image description here

deef0000dragon1
  • 309
  • 4
  • 14
Ryan Schaefer
  • 2,692
  • 1
  • 19
  • 41