Click here to Skip to main content
14,937,632 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a text to enter phone number.

when I give number 8888888888
it should be converted to (888)888-8888 this format.

How can I achieve this using javascript or jquery?
Updated 30-Oct-19 9:21am

Here is clear cut solution

Masked Input[^]

Here is manual js: This works on onblur:

<script src=""
    <script type="text/javascript">
        function formatPhone(obj) {
            var numbers = obj.value.replace(/\D/g, ''),
        char = { 0: '(', 3: ') ', 6: ' - ' };
            obj.value = '';
            for (var i = 0; i < numbers.length; i++) {
                obj.value += (char[i] || '') + numbers[i];

And HTMl Code:
<input type="text" name="test"  önblur="formatPhone(this);" />
syna syna 8-Apr-14 8:52am
can I get any other solution without using MaskedInput.js?
Er. Puneet Goel 8-Apr-14 8:57am
yes you can. But using masking is much preferred. But still if you need, let me know?
syna syna 9-Apr-14 1:18am
yes i want in javascript i dont want to use Maskedinput js
Er. Puneet Goel 9-Apr-14 3:20am
I have modified the solution, please check and mark solution accordingly. Let me know if any issue is there?
You can use regular expression, below link is having the solution of same issue.[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900