I have the following code. I am trying to have the regular express test the phone number for validation. With the current argument the function should return positive, but it doesn't and I can't figure out why.
function telephoneCheck(str) {
let reg = /^[\d]{0,1}[\w]{0,1}[(]{0,1}[\d]{3}[-)\w]{0,2}[\d]{3}[-\w]{0,1}[\d]/;
return reg.test(str);
}
console.log("function: " telephoneCheck("1 (555) 555-5555"));
Can anyone see what I am missing?
CodePudding user response:
First, replace all the \w
(Matches any letter, digit or underscore) with \s
(Matches any space, tab or newline character). I believe you don't won't letter in phone number.
Second, you need to add a quantifier {0,4}
to the end of your Regex, just like you already did in other positions of the Regex.
So the final Regex will be ^[\d]{0,1}[\s]{0,1}[(]{0,1}[\d]{3}[-)\s]{0,2}[\d]{3}[-\s]{0,1}[\d]{0,4}
CodePudding user response:
Because your regex is nonsense.
- No need for
[]
for single group ([\d]{0,1}
can be just\d?
\w
does not match spaces, just[a-z0-9]
in general case- You match starting
(
but ending)
can be followed by-
or any\w
function telephoneCheck(str) {
let reg = /^\d?\s?\(?[\d-] \)?\s?\d /;
return reg.test(str);
}
console.log("function: " telephoneCheck("1 (555) 555-5555"));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
- You need to replace
\w
with\s
for whitespace - You need to escape parenthesis
\(
and\)
- You need to change
[-)\w]{0,2}
to[-\)]{0,1}[\s]{0,1}
unless you want the unorthodox 1 (555)-555-5555 to be true. - The final
[\d]
should be[\d]{4}
since you want exactly 4 digits at the end. - You can replace the
{0,1}
with?
when evaluating a single character that is optional. - You don't need brackets around single characters.
Here's the resulting code:
function telephoneCheck(str) {
let reg = /^\d?\s?\(?\d{3}[-\)]{0,1}\s?\d{3}[-\s]?\d{4}/;
return reg.test(str);
}
console.log(telephoneCheck("1 (555)555-5555")); // true
console.log(telephoneCheck("1 (555)5555555")); // true
console.log(telephoneCheck("(555)555-5555")); //true
console.log(telephoneCheck("15555555555")); //true
console.log(telephoneCheck("1 (555)555- 5555")); // false
console.log(telephoneCheck("1 (555)-555-5555")); // false
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>