'Insert hyphens in JavaScript

What is the easiest way to insert hyphens in JavaScript?

I have a phone number eg. 1234567890

While displaying in the front-end, I have to display it as 123-456-7890 using JavaScript.

What is the simplest way to achieve this?



Solution 1:[1]

Quickest way would be with some regex:

Where n is the number

n.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");

Example: http://jsfiddle.net/jasongennaro/yXD7g/

var n = "1234567899";
console.log(n.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3"));

Solution 2:[2]

Given this kind of input, an other way would be:

var phone = "1234567890";
phone = phone.replace(/(\d{3})(\d{3})(\d+)/, '$1-$2-$3');

Of course this does not work if your input changes.

Solution 3:[3]

You could use the substr-function to achieve this, assumed that the hyphens are always inserted on the same position:

var hypString = phonestr.substr(0,3) + '-' + phonestr.substr(3, 6) + '-' + phonestr.substr(6);

Solution 4:[4]

You can create a javascript function to format the phone number. Something like this:

    function formatPhoneStr(o)
    {
        var strPhone = o.value;

        if( (strPhone != null) && (strPhone.length > 0) && (strPhone.indexOf('(') == -1))
        {
            if (strPhone.length == 10)
            {
                strPhone = '(' + strPhone.substr(0,3) + ') ' + strPhone.substr(3,3) + '-' + strPhone.substr(6,4);
            }
            else if (strPhone.length > 10)
            {
                strPhone = '(' + strPhone.substr(0,3) + ') ' + strPhone.substr(3,3) + '-' + strPhone.substr(6,4) + ' x' + strPhone.substr(10);
            }
            o.value = strPhone;
        }
    }

Solution 5:[5]

Another alternative that I believe is the cleanest one: the slice string method.

formattedPhone = phone.slice(0,3) + '-' + phone.slice(3, 6) + '-' phone.slice(6)

The first parameter is the start position in the string, the second is the end position. As you can see above, no parameters it goes till the end of the string. A nice feature is that, like Python, negative positions count from the end of the string. This can make your code somewhat more robust:

formattedPhone = phone.slice(0,3) + '-' + phone.slice(3, -4) + '-' + phone.slice(-4)

Even if you got a phone with 9 or 11 digits it will look nice.

Solution 6:[6]

If you want to mask your input in that way then you can do something like below so that when input is being given by the user it automatically formats it to the required format.

function transform(){
 let ele = document.getElementById("phno");
 ele.value = ele.value.replace(/^(\d{3})$/g, '$1-')
      .replace(/^(\d{3}\-\d{3})$/g, '$1-');
}
<input
  type="text"
  onkeyup="transform()"
  id="phno"
  placeholder="123-123-4444"
  maxlength="12"
/>

Solution 7:[7]

try this...

<input required type="tel" maxlength="12" onKeypress="addDashesPhone(this)" name="Phone" id="Phone">    

function addDashesPhone(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;
}

Solution 8:[8]

For react just use a ref like this example:

Here I just replace the value of the element and include hyphens onBlur

Logic part:

    const ref = React.useRef(null)

    const blurHandle = () => {
        ref.current.value = ref.current.value.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")
    };

declarative render part:

<Input
  ref={phoneInput}
  onFocus={focusHandler}
  onBlur={blurHandle}
  type="tel"
  placeholder="###-###-####"
  name="from_phoneNumber"
  pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
/>

If your Input is a sepparated styled component using an input JSX element inside remember pass the ref to the children element using a foward ref

const Input = React.forwardRef((props, ref) => (
    <input type="tel" ref={ref} ........ />
))

Solution 9:[9]

If you're using the ASP.NET client library they have a great String.format method that provides locale formats and all kinds of fancy stuff. The method is called as you'd expect if you're familiar with .NET:

<script type="text/javascript">
    var myPhone = String.format("{0}-{1}-{2}", firstThree, secondThree, lastFour);
</script>

If you're not using ASP.NET library, I'm sure you could get the rudimentary formatting done in your own implementation - obviously this would be sans localization and you should throw some error handling/checking in the mix:

function format(str, arr){
     for(var i = 0; i < arr.length; i++) {
         var r = new RegExp("\\{" + i + "\\}", "g");
         str = str.replace(r,arr[i]);
    }
    return str;
}
alert(format("{0}-{1}-{2}", [123,456,7890]));

Solution 10:[10]

here's my solution just in case it helps someone:

validatePhone: function (e) {

    var number = this.$el.find('#phoneNumberField').val().replace(/-/g, '');

    if(number.length > 10) {
        e.preventDefault();
    }

    if(number.length < 3) {
        number = number; // just for legibility
    } else if(number.length < 7) {
        number = number.substring(0,3) + 
        '-' + 
        number.substring(3,6)
    } else if(number.length > 6) {
        number = number.substring(0,3) + 
        '-' + 
        number.substring(3,6) + 
        '-' + 
        number.substring(6,10);
    }

    this.$el.find('#phoneNumberField').val(number);

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 brk
Solution 2 Felix Kling
Solution 3 GNi33
Solution 4 tschubach
Solution 5 neves
Solution 6 SaiSurya
Solution 7 michael g
Solution 8 Rolando Niubó
Solution 9 Brian
Solution 10 Benjamin McFerren