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
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:
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:
here's my solution just in case it helps someone:
validatePhone: function (e) {
}
Given this kind of input, an other way would be:
Of course this does not work if your input changes.
Another alternative that I believe is the cleanest one: the
slice
string method.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:
Even if you got a phone with 9 or 11 digits it will look nice.
You could use the substr-function to achieve this, assumed that the hyphens are always inserted on the same position:
You can create a javascript function to format the phone number. Something like this: