Skip to content

Instantly share code, notes, and snippets.

@JaymesKat
Last active December 27, 2019 02:30
Show Gist options
  • Save JaymesKat/0ad5dde5a50e732212f844b7570d0c1b to your computer and use it in GitHub Desktop.
Save JaymesKat/0ad5dde5a50e732212f844b7570d0c1b to your computer and use it in GitHub Desktop.
A function that returns true if the passed string looks like a valid US phone number.
function telephoneCheck(str) {
if(!parenthesesBalanced(str)){
return false;
}
const regex = /^1?\s*(\(?\d{3}\)?[-]?\s*){2}\d{4}$/
return regex.test(str);
}
function parenthesesBalanced(str){
const openBracketRegex = /\(/g
const closeBracketRegex = /\)/g
let result1 = str.match(openBracketRegex)
let result2 = str.match(closeBracketRegex)
if(!result1){
result1 = []
}
if(!result2){
result2 = []
}
return result1.length == result2.length
}
telephoneCheck("555-555-5555");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment