Skip to content

Instantly share code, notes, and snippets.

@patricknowlan
Created March 15, 2016 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patricknowlan/9cd3874875b934735f42 to your computer and use it in GitHub Desktop.
Save patricknowlan/9cd3874875b934735f42 to your computer and use it in GitHub Desktop.
Phone number filter, removes special characters, removes spaces, returns "N/A" if no phone number. For US phone numbers only.
//Example of how to use the filter
<span> {{vm.phone_number | phonenumber}}</span>
//Example of how to add the filter
(function() {
'use strict';
angular
.module('app.core')
.filter('phonenumber', function() {
/*
Format phonenumber as: c (xxx) xxx-xxxx
or as close as possible if phonenumber length is not 10
if c is not '1' (country code not USA), does not use country code
*/
return function (number) {
/*
@param {Number | String} number - Number that will be formatted as telephone number
Returns formatted number: (###) ###-####
if number.length < 4: ###
else if number.length < 7: (###) ###
Does not handle country codes that are not '1' (USA)
*/
//Removes special characters and spaces
number = String(number).replace(/[^0-9]/g, "");
/Returns N/A if no phone number is present
if (!number) { return 'N/A'; }
// Will return formattedNumber.
// If phonenumber isn't longer than an area code, just show number
var formattedNumber = number;
// if the first character is '1', strip it out and add it back
var c = (number[0] == '1') ? '1 ' : '';
number = number[0] == '1' ? number.slice(1) : number;
// # (###) ###-#### as c (area) front-end
var area = number.substring(0,3);
var front = number.substring(3, 6);
var end = number.substring(6, 10);
if (front) {
formattedNumber = (c + "(" + area + ") " + front);
}
if (end) {
formattedNumber += ("-" + end);
}
return formattedNumber;
};
});
})();
//Credit to Alexandra Burke for original version
https://gist.github.com/aberke/042eef0f37dba1138f9e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment