phone number formatter javascript grepper code example
Example 1: phone number formatter javascript grepper
// Checks if a string is a valid americain phone number
var phoneFormatter = function(phoneNumber) {
var counter;
var current;
var phoneNumberLength = phoneNumber.length;
var digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
var delimiter = "-";
if( typeof phoneNumber !== "string" || phoneNumberLength !== 8) return false;
for(counter = 0; counter < phoneNumberLength; counter++) {
current = phoneNumber[counter];
if(digits.indexOf(current) === -1) {
if (phoneNumber[3] === delimiter) {
return true;
} else if(current !== delimiter) {
return false;
}
}
}
return true;
}
Example 2: phone number formatter javascript grepper
// Checks if a string is a valid americain phone number with regex
var phoneFormatterRegex = function (phoneNumber) {
return /^\d{3}-\d{4}$/.test(phoneNumber);
}