showing results for - "phone number formatter javascript grepper"
Oona
17 May 2020
1// Checks if a string is a valid americain phone number
2
3var phoneFormatter = function(phoneNumber) {
4    var counter;
5    var current;
6    var phoneNumberLength = phoneNumber.length;
7    var digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
8    var delimiter = "-";
9    
10    if( typeof phoneNumber !== "string" || phoneNumberLength !== 8) return false;
11    for(counter = 0; counter < phoneNumberLength; counter++) {
12        current = phoneNumber[counter];
13        if(digits.indexOf(current) === -1) {
14            if (phoneNumber[3] === delimiter) {
15                return true;
16            } else if(current !== delimiter) {
17                return false;
18            }
19        }
20    }   
21    
22    return true;
23}
Wassim
05 Jan 2017
1// Checks if a string is a valid americain phone number with regex
2
3var phoneFormatterRegex = function (phoneNumber) {
4  return /^\d{3}-\d{4}$/.test(phoneNumber);
5}