var nums_to_try = [
'2159018060',
'(215) 901 8060',
'(215)-901-8060',
'1.215.901.8060',
'+1-215-9018060',
'+1-215-901-8060 x233',
'+1-215-901-8060 Ext 233',
'+44 20 7323 8299'
]; //quick test to make sure all demonstrated cases are input
$(document).ready(function() {
var numbers = [{
name: 'phone10', //property was mostly used for debug. you can probably remove this without any errors
pattern: /^([0-9]{3})\-?([0-9]{3})\-?([0-9]{4})(ext|x)?([0-9]+)?$/i,
//starts with 3 numbers, another 3 numbers, then 4 numbers. we either have ext or x, and then some more numbers (though we don't know how many)
replace: '$1-$2-$3 $4 $5' //If $4 and $5 aren't there we remove the extra space with the .trim() call at the end.
}, {
name: 'phone12',
pattern: /(\+[0-9]{2})([0-9]{2})([0-9]{4})([0-9]{4})/,
//a group of two with a plus, another group of two, and then 2 groups of 4.
replace: '$1 $2 $3 $4'
}]; //Array of number maps
var not_allowed = [
/\./g, //no dots.
/^\+?1-?/g, //removes leading 1's with option +1 or 1- or +1- syntax
/[\(\)\-\s]/g //gets rid of both parenthesis characters, hyphens, and spaces.
]; //Array of not allowed characters
var remove_not_allowed = function(str, n) {
//str we are using,
//patterns or strings we are not allowing. We simply erase them.
$.each(n, function(i, ni) {
str = str.replace(ni, '');
}); //Loops through each object in n, replacing it.
return str;
};
var mapped_nums = $.map(nums_to_try, function(phone) {
var phone = remove_not_allowed(phone, not_allowed);
//gets rid of all our non-allowed characters or matches
$.each(numbers, function(i, rep) {
//loops through each phone number array
if (phone.match(rep.pattern)) { //Check that the pattern applies, otherwise nothing is going to work.
phone = phone.replace(rep.pattern, rep.replace);
//if it matches, replace.
return; //if it matches, we don't want duplicate matches so we end.
}
});
return phone.trim(); //returns our trimmed out phone number
}); //end $.map call
console.log(mapped_nums); //console check just to make sure we aren't adding any spaces to the end of our strings.
$('#results').html(mapped_nums.join('\n')); //Quick way to test our results.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="results">
2159018060 -> 215-901-8060
(215) 901 8060-> 215-901-8060
(215)-901-8060-> 215-901-8060
1.215.901.8060 -> 215-901-8060
+1-215-9018060 -> 215-901-8060
+1-215-901-8060 x233 -> 215-901-8060 x233
+1-215-901-8060 Ext 233 -> 215-901-8060 Ext 233
+44 20 7323 8299 -> +44 20 7323 8299
</pre>