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?
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}
Because your regex is nonsense.
[] for single group ([\d]{0,1} can be just \d?\w does not match spaces, just [a-z0-9] in general case( but ending ) can be followed by - or any \wfunction telephoneCheck(str) {
let reg = /^\d?\s?\(?[\d-]+\)?\s?\d+/;
return reg.test(str);
}
console.log("function: " + telephoneCheck("1 (555) 555-5555"));
\w with \s for whitespace\( and \)[-)\w]{0,2} to [-\)]{0,1}[\s]{0,1} unless you want the unorthodox 1 (555)-555-5555 to be true.[\d] should be [\d]{4} since you want exactly 4 digits at the end.{0,1} with ? when evaluating a single character that is optional.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