Question one (formatting telephone number):
I\'m having to format a telephone number in AngularJS but there is no filter for it. Is there a way to u
I solved this problem with a custom Angular filter as well, but mine takes advantage of regex capturing groups and so the code is really short. I pair it with a separate stripNonNumeric filter to sanitize the input:
app.filter('stripNonNumeric', function() {
return function(input) {
return (input == null) ? null : input.toString().replace(/\D/g, '');
}
});
The phoneFormat filter properly formats a phone number with or without the area code. (I did not need international number support.)
app.filter('phoneFormat', function() {
//this establishes 3 capture groups: the first has 3 digits, the second has 3 digits, the third has 4 digits. Strings which are not 7 or 10 digits numeric will fail.
var phoneFormat = /^(\d{3})?(\d{3})(\d{4})$/;
return function(input) {
var parsed = phoneFormat.exec(input);
//if input isn't either 7 or 10 characters numeric, just return input
return (!parsed) ? input : ((parsed[1]) ? '(' + parsed[1] + ') ' : '') + parsed[2] + '-' + parsed[3];
}
});
Use them simply:
{{customer.phone | stripNonNumeric | phoneFormat}}
The regex for the stripNonNumeric filter came from here.