Javascript dashes in phone number

javascript

Solution

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);
}

Problem

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> ```

Original source

Related problems