How to format phone number (xxx) xxx-xxxx in javascript

    To format phone number in javascript you can use following function
    function phoneFormatter(phoneNumber) {
        var numbers = phoneNumber.replace(/\D/g, ''),
            char = { 0: '(', 3: ') ', 6: ' - ' };
        phoneNumber = '';
        for (var i = 0; i < numbers.length; i++) {
            phoneNumber += (char[i] || '') + numbers[i];
        }
        return phoneNumber;
    }


    var phoneNumber = "1234567890";

    console.log("Phone Number:", phoneFormatter(phoneNumber));
    So the output will be: Phone Number: (123) 456-7890 It can accept any number like 1234567890, (123) 456-7890, 123-456-7890 etc
    5
    Average: 5 (1 vote)