Formatting phone number with angular

format a 10 digit number with angularjs

by Zareh Geertjes

HTML

<div ng-app>

    <div ng-controller="Ctrl">

        <label>Enter a telephone number to format:</label>
        <input ng-model="phoneNumber" ng-bind="phoneNumber | tel" /><br><br>
           Result formatted: {{ phoneNumber | tel }}
    </div>
</div>

JavaScript

angular.module('ng').filter('tel', function () {
    return function (tel) {
        if (!tel) { return ''; }

        var value = tel.toString().trim().replace(/^\+/, '');

        if (value.match(/[^0-9]/)) {
            return tel;
        }

        var country, mobile, number;

        switch (value.length) {

            case 10: // +1PPP####### -> C (PPP) ###-####
                country = 1;
                mobile = value.slice(0, 2);
                number = value.slice(2);
                break;

            case 12: // +CCCPP####### -> CCC (PP) ###-####
                country = value.slice(0, 2);
                mobile = value.slice(2, 4);
                number = value.slice(4);
                break;

            default:
                return tel;
        }

        if (country == 1) {
            country = "";
        }else{
            country = "+"+country+" ";
            mobile = "("+mobile.slice(0, 1)+")"+mobile.slice(1);
        }

        return (country + mobile + " - " + number).trim();
    };
});

function Ctrl($scope){
    $scope.phoneNumber =  '';
}