20

I tried to research the answer to this question but I'm lost. I am trying to make a one search bar that automatically puts a dash in the phone number. I've solved that.

The next part is the challenging part. How can I make it always do XXX-XXX-XXXX, even if the characters pasted were something like 555 555 1212 or 555---555-1212, where it will only reel back the number and output with 555-555-1212. It shouldn't count the spaces or extra dashes as a character.

I found: http://www.jotform.com/answers/15202-can-I-add-script-to-my-form-that-will-automatically-add-hyphens-in-between-the-3-digit-area-code-and-also-the-3-digit-prefix

I changed it just a bit by adding:

<SCRIPT LANGUAGE="JavaScript">
        function addDashes(f)
            {
                f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
            }
    </SCRIPT>


<input id="input_4" class="form-textbox" maxlength="15" name="atn" size="25" onBlur='addDashes(this)' />

Right now, this works only if the user puts 5555555555 and automatically turns it into 555-555-5555. I'm trying to figure out how to take something like 5-55555-5555 and turn it into 555-555-5555. Currently, it makes it 5-5-555-5-5555.

See my dilemma? lol. It can't be php or any server side scripting as this must be able to run on a desktop.


Resolution:

<SCRIPT LANGUAGE="JavaScript">
        function addDashes(f)
            {
                f.value = f.value.replace(/\D/g, '');

                f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
            }
    </SCRIPT>
traveler84
  • 453
  • 2
  • 4
  • 15
  • 3
    Step one would be to "cleanse" the input, such as using a simple regex matching to remove anything that's not a number from the input (e.g. `input.replace(/[^0-9]+/g, '');`) – Cᴏʀʏ Oct 26 '12 at 19:28
  • I made it 15 characters to give extra room for misc characters or spaces. – traveler84 Oct 26 '12 at 19:28
  • i hate to break it to you but i've tackled this problem before and the solution is not simple by any definition, especially if you want to support all major browsers (IE8). – jbabey Oct 26 '12 at 19:31
  • @jbabey: What? This seems pretty trivial to me, unless you're talking about handling paste events and such... – Cᴏʀʏ Oct 26 '12 at 19:33
  • @Cory you need to handle cut, copy, paste, keyup, keydown, keypress, blur, and change. this is assuming you want a fully working solution - hacking on a partially-working keyup handler is obviously much simpler. – jbabey Oct 26 '12 at 19:34
  • Just one browser needed. Not a website. Just needs support for say IE8/9. – traveler84 Oct 26 '12 at 19:34
  • @JoshuaSheehan - That's two browsers. :) – JDB Oct 26 '12 at 19:42

7 Answers7

27

First, clean your input by deleting all chars that are not numbers (ref.: Regex to replace everything except numbers and a decimal point)

Then, you put your dashes.

function addDashes(f)
{
    f_val = f.value.replace(/\D[^\.]/g, "");
    f.value = f_val.slice(0,3)+"-"+f_val.slice(3,6)+"-"+f_val.slice(6);
}
Community
  • 1
  • 1
Matheus Azevedo
  • 878
  • 7
  • 18
  • 1
    Ok, slight change but this led me to the right direction. I found a cleaning code that wipes everything but numbers. Then, the other code to put the dashes. It removed every character I threw in it. – traveler84 Oct 26 '12 at 19:56
  • Anyone having issues with using backspace with this code just throw this in the mix var key = event.which || event.keyCode || event.charCode; if (key != 8) {\\add dashes code} – Preston Apr 08 '13 at 03:44
  • @Preston expanding on that, you can also add `&& key != 46` to the condition to account for the `DEL` key. – keeehlan Apr 01 '16 at 21:21
  • When calling the function just pass the element we don't need to pass element.value (ex. addDashes(elem) -- not addDashes(elem.value). Super stellar function; greatly appreciate your answer Matheus Azevedo! – Catto Jul 29 '16 at 11:41
8

I have a strong tendency to treat phone numbers as a straight string of 10 digits with no formatting (so I can apply formatting to them on-the-fly, as needed and so searching and comparison is simpler), although that may change if I ever have to deal with international phone numbers. If all you're dealing with is US phone numbers, this will work nicely (formats it as it's typed):

function addDashes(f) {
    var r = /(\D+)/g,
        npa = '',
        nxx = '',
        last4 = '';
    f.value = f.value.replace(r, '');
    npa = f.value.substr(0, 3);
    nxx = f.value.substr(3, 3);
    last4 = f.value.substr(6, 4);
    f.value = npa + '-' + nxx + '-' + last4;
}​

Here's a fiddle: http://jsfiddle.net/EYuk5/

pete
  • 24,141
  • 4
  • 37
  • 51
  • This still does the same with the dashes in the one field. – traveler84 Nov 19 '12 at 18:07
  • 1
    @JoshuaSheehan: I'm confused. Over three weeks ago, you accepted freon's answer. Why leave your comment **now** on my apparently previously non-helpful answer. What's the purpose? Are you still having problems formatting phone numbers? – pete Nov 19 '12 at 19:45
  • I actually used onkeypress instead of onKeyUp so that i could also delete the number. – Serge Pedroza May 29 '14 at 00:57
  • @pete : In the demo you have shown on jsfiddle, once we type some number and delete the input we can only delete the number but the dashes were not deleted. Is there any way to delete those dashes as well? – Raj Baral Aug 03 '17 at 21:40
  • @RajBaral -- sure is. Just replace the last line of his function with this line and it makes it all around better imo:f.value = npa + (nxx.length > 0 ? '-' : '') + nxx + (last4.length > 0 ? '-' : '') + last4; – Uncle Iroh Sep 26 '17 at 21:58
  • @RajBaral, the comment by [Uncle Iroh](https://stackoverflow.com/users/477494/uncle-iroh) should work, or you could also do something like this: [updated fiddle](http://jsfiddle.net/EYuk5/407/) – pete Sep 27 '17 at 13:08
4

transform with string method replace

let phone = '0884332212'.replace(/^(\d{3})(\d{3})(\d{4})/, '$1-$2-$3')
console.log(phone)
// => 088-433-2212
Anecha Sun
  • 105
  • 1
  • 2
1

I did this

function addDashesToNumber(number){
    const numWithoutDashes = number.replace(/[^0-9]/g, '')
    if(numWithoutDashes.length > 10) return number.slice(0, -1)
    const dashPlaces = [3, 6]
    return numWithoutDashes
                .split('')
                .reduce((acc, curr, i) => dashPlaces.includes(i) ? [...acc, '-', curr] : [...acc, curr], [])
                .join('')
}
Josh Tal
  • 11
  • 3
0

Try this:

  function dashedNumber(value){
    const afterIndices = [3,6,8]; 
    const length = value.length;
    let newValue = '' 
    for(let i=0; i<length; i++){
      if(afterIndices.includes(i))
        newValue+='-'
      newValue+=value[i];
    }
    return newValue;
  }
Ankit Kumar Ojha
  • 2,296
  • 2
  • 22
  • 30
0

Here's a fiddle: https://jsfiddle.net/v9gq5jkw/.

<input id="phone">
function phone_formatting(ele, restore) {
  var new_number,
    selection_start = ele.selectionStart,
    selection_end = ele.selectionEnd,
    number = ele.value.replace(/\D/g, '');

  if (number.length > 2) {
    new_number = number.substring(0, 3) + '-';
    if (number.length === 4 || number.length === 5) {
      new_number += number.substr(3);
    } else if (number.length > 5) {
      new_number += number.substring(3, 6) + '-';
    }
    if (number.length > 6) {
      new_number += number.substring(6);
    }
  } else {
    new_number = number;
  }

  ele.value = (new_number.length > 12) ? new_number.substring(0, 12) : new_number;

  if (new_number.slice(-1) === '-' && restore === false &&
    (new_number.length === 8 && selection_end === 7) ||
    (new_number.length === 4 && selection_end === 3)) {
    selection_start = new_number.length;
    selection_end = new_number.length;
  } else if (restore === 'revert') {
    selection_start--;
    selection_end--;
  }
  ele.setSelectionRange(selection_start, selection_end);

}

function phone_number_check(field, e) {
  var key_code = e.keyCode,
    key_string = String.fromCharCode(key_code),
    press_delete = false,
    dash_key = 189,
    delete_key = [8, 46],
    direction_key = [33, 34, 35, 36, 37, 38, 39, 40],
    selection_end = field.selectionEnd;

  if (delete_key.indexOf(key_code) > -1) {
    press_delete = true;
  }

  if (key_string.match(/^\d+$/) || press_delete) {
    phone_formatting(field, press_delete);
  } else if (direction_key.indexOf(key_code) > -1) {} else if (dash_key === key_code) {
    if (selection_end === field.value.length) {
      field.value = field.value.slice(0, -1)
    } else {
      field.value = field.value.substring(0, (selection_end - 1)) + field.value.substr(selection_end)
      field.selectionEnd = selection_end - 1;
    }
  } else {
    e.preventDefault();
    phone_formatting(field, 'revert');
  }

}

document.getElementById('phone').onkeyup = function(e) {
  phone_number_check(this, e);
}

-2

Beside adding dashes, you will need to deal with the position of the cursor, especially in case of deletion.

This AMD module does exactly that: https://github.com/whenyoubelieve2014/us-telephone-input

Believe2014
  • 3,894
  • 2
  • 26
  • 46