benjamincharity
7/17/2015 - 4:46 PM

Filter to format or clean a phone number.

Filter to format or clean a phone number.

angular.module('common')
.filter('telephone', function() {
    'use strict';


    /**
     * Clean or format a telephone number
     *
     * @param {String} number
     * @param {String} method
     * @return {String} finalNumber
     */
    return function(tel, method) {

        // Return if no number was passed in
        if (!tel) {
            return '';
        }

        // Strip all non-numeric characters
        var value = tel.toString().trim().replace(/\D/g, '');

        // Return if no method was passed in
        if (!method) {
            return 'A method{string} is required. e.g. \'clean\' or \'format\'';
        }


        //
        // Clean a phone number
        if (method === 'clean') {
            return parseInt(value, 10);
        }


        //
        // Format a phone number
        if (method === 'format') {

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

            var country;
            var city;
            var number;

            switch (value.length) {
                case 1:
                    case 2:
                    case 3:
                    city = value;
                break;

                default:
                    city = value.slice(0, 3);
                number = value.slice(3);
            }

            if (number) {

                if (number.length > 3) {
                    number = number.slice(0, 3) + '-' + number.slice(3,7);
                } else {
                    number = number;
                }

                return ('(' + city + ') ' + number).trim();

            } else {
                return '(' + city;
            }

        }

    };

});