Insert hyphens in javascript

2019-02-04 08:13发布

问题:

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 and the quickest way to achieve this?

Thanks

回答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"));



回答2:

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


回答3:

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.



回答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;
        }
    }


回答5:

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


回答6:

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.



回答7:

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


回答8:

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

}