Javascript Regular Expression to add dash after every 3rd and 4th characters

16,507

Solution 1

How about

> "12345678".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-78"
> "123456789".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-789"
> "1234567890".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-7890"

Solution 2

Do you need to use regular expressions for everything or would maybe something like this also help you out?

function convertToValidPhoneNumber(text) {
    var result = [];
    text = text.replace(/[^\d]/g,"");
    while (text.length >= 6) {
        result.push(text.substring(0, 3));
        text = text.substring(3);
    }
    if(text.length > 0) result.push(text);
    return result.join("-");
}

You could use this function everytime the text in your inputfield changes. It will produce the following results:

"12345678" -> "123-45678"
"123d456789" -> "123-456-789"
"123-4567-89" -> "123-456-789"
Share:
16,507
GGio
Author by

GGio

Updated on June 18, 2022

Comments

  • GGio
    GGio almost 2 years

    The following regex:

    x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, "-"); 
    

    adds dash after each 3rd character so entered 123456789 turns into 123-456-789. Im trying to use this regex to format phone number. The problem arises on the 10th character. So entered 1234567890 turns into 1-234-567-890.

    How would I modify the above regex to turn strings that have 10 digits into 123-456-7890. I use this regex because this happens as user is typing in uses keyup event.

    If you know easier or better way of doing this please help me out, dashes has to be added while user is typing in. No other characters allowed.

    Notes:

    1. Cant use Jquery Masked input plugin (because if editing the middle character it's focus gets messed up)
  • GGio
    GGio almost 11 years
    works but If i remove/add digit from middle and add digit it does not reformat it. Example: "123-456-7890" added number 1 next to 5 gives result: "123-4516-7890" should not allow
  • georg
    georg almost 11 years
    @GGio: remove the dashes first val=val.replace(/-/g,'') and then reformat.
  • Jaison James
    Jaison James over 5 years
    123-4567890, Pls help me to get a result like this. Only insert hyphen after the first n digit
  • Zsolt Meszaros
    Zsolt Meszaros over 3 years
    Why are you screaming on all your answers today? Please, edit your answer and use lowercase instead of UPPERCASE.
  • Hassan Qasim
    Hassan Qasim over 3 years
    @ZsoltMeszaros it's just because of caps, btw why is it important to write in lowercase?
  • Zsolt Meszaros
    Zsolt Meszaros over 3 years
    Because messages typed completely in capital letters are equated to shouting and other argumentative behaviours.