Last active
March 3, 2017 05:48
-
-
Save popcorn245/7a230b447a789c206458 to your computer and use it in GitHub Desktop.
Phone Number Formatter TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="../tsd/angularjs/angular.d.ts"/> | |
module AppName { | |
class TelFilter { | |
constructor(tel) { | |
if (!tel) { return ''; } | |
var value = tel.toString().trim().replace(/^\+/, ''); | |
if (value.match(/[^0-9]/)) { | |
return tel; | |
} | |
var country, city, number; | |
switch (value.length) { | |
case 10: // +1PPP####### -> C (PPP) ###-#### | |
country = 1; | |
city = value.slice(0, 3); | |
number = value.slice(3); | |
break; | |
case 11: // +CPPP####### -> CCC (PP) ###-#### | |
country = value[0]; | |
city = value.slice(1, 4); | |
number = value.slice(4); | |
break; | |
case 12: // +CCCPP####### -> CCC (PP) ###-#### | |
country = value.slice(0, 3); | |
city = value.slice(3, 5); | |
number = value.slice(5); | |
break; | |
default: | |
return tel; | |
} | |
if (country === 1) { | |
country = ''; | |
} | |
number = number.slice(0, 3) + '-' + number.slice(3); | |
return (country + ' (' + city + ') ' + number).trim(); | |
}; | |
} | |
angular.module('AppName').filter('tel', function(){ | |
return TelFilter; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment