-
-
Save cmcnealy/8383815eb9a1b62b66b502cf392ae2bd to your computer and use it in GitHub Desktop.
function telephoneCheck(str) { | |
// regex that matches a phone number with no spaces, | |
// with spaces, with dashes, and with or without country code | |
let regex = /^[1]*[\s|-]*\d{3}[\s|-]*\d{3}[\s|-]*\d{4}$/; | |
// regex that matches parentheses | |
// with no spaces, with spaces, with dashes, | |
// and with or without country code | |
let regexParentheses = /^[1]*[\s]*[(]\d{3}[)][\s]*\d{3}[\s|-]*\d{4}$/; | |
if (!regex.test(str)) { | |
return regexParentheses.test(str); | |
} else { | |
return true; | |
} | |
} | |
telephoneCheck("1 (555) 555-5555"); // returns true | |
telephoneCheck("1 555)555-5555") // returns false |
why is the last one return false
why is the last one return false
Last one is not considered valid because there is no opening bracket.
Para validar también el último caso deberíamos aregar: ^[1]?
Es decir el patrón quedaría así -> /^[1]?(\s)(\d{3})+[-|\s](\d{3})+[-|\s]*\d{4}$/;
Con '?' nos aseguramos que si viene el 1, sea 1 vez.
Got it in 1 line if anyone is interested:
return /^(1 |1)?((\d{3})|(\(\d{3}\)))(-| |)(\d{3})(-| |)(\d{4})$/.test(str)
Another way:
function telephoneCheck(str) {
let regex = /^(1 |1)?((\d{3})|((\d{3})))(-| |)(\d{3})(-| |)(\d{4})$/;
return (regex.test(str)==true)
}
console.log(telephoneCheck("1 (555) 555-5555")) // returns true
console.log(telephoneCheck("1 555)555-5555")) // returns false
Got it in 1 line if anyone is interested:
return /^(1 |1)?((\d{3})|(\(\d{3}\)))(-| |)(\d{3})(-| |)(\d{4})$/.test(str)
very very good^ super
Got it in 1 line if anyone is interested:
return /^(1 |1)?((\d{3})|(\(\d{3}\)))(-| |)(\d{3})(-| |)(\d{4})$/.test(str)
very very good^ super
@RihardXXX Thanks for that, I was going the long route.
Got it in 1 line if anyone is interested:
return /^(1 |1)?((\d{3})|((\d{3})))(-| |)(\d{3})(-| |)(\d{4})$/.test(str)
You are incredible.
alternative:``
function telephoneCheck(str) {
let regex = /^(1\s?)?(\(\d{3}\)|\d{3})([\s\-]?)\d{3}([\s\-]?)\d{4}$/;
return regex.test(str);
}
console.log(telephoneCheck("1 (555) 555-5555")); // returns true
console.log(telephoneCheck("1 555)555-5555")); // returns false
return /^(1 |1)?((\d{3})|((\d{3})))(-| |)(\d{3})(-| |)(\d{4})$/.test(str)
Thanks a lot...your supperb.
Got it in 1 line if anyone is interested:
return /^(1 |1)?((\d{3})|(\(\d{3}\)))(-| |)(\d{3})(-| |)(\d{4})$/.test(str)
Wonderfully done!
excellent