Insert hyphens in javascript

2019-02-04 07:15发布

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

8条回答
迷人小祖宗
2楼-- · 2019-02-04 08:15

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;
}
查看更多
beautiful°
3楼-- · 2019-02-04 08:17

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

查看更多
登录 后发表回答