Mask US phone number string with JavaScript

扶醉桌前 提交于 2019-11-26 09:34:43

问题


I need regular express for US Phone Number format.I want to replace the phone number string into below US phone number string format in JavaScript.

var number = \"4031234789\";

And I want to mask it in below format:-

number = number.mask(\'(000) 000-0000\');

Can anyone show me a regular expression for that in JavaScript?


回答1:


This answer assumes you want the following format: (000) 000-0000 (as the OP states).

There are multiple different ways to implement this, but here are a couple different approaches:


If you want to simply mask the number on the blur event (when the field loses focus), then you could use the following:

document.getElementById('phone').addEventListener('blur', function (e) {
  var x = e.target.value.replace(/\D/g, '').match(/(\d{3})(\d{3})(\d{4})/);
  e.target.value = '(' + x[1] + ') ' + x[2] + '-' + x[3];
});
<p>Masked on the blur event (remove focus).</p>
<input type="text" id="phone" placeholder="(555) 555-5555"/>

Alternatively, if you would rather mask the number while typing, you can listen to the input event and then conditionally mask the number based on the regex match:

document.getElementById('phone').addEventListener('input', function (e) {
  var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
<input type="text" id="phone" placeholder="(555) 555-5555"/>



回答2:


You can use regular expression and then concatenate to form your string.

var USNumber = "4031234789".match(/(\d{3})(\d{3})(\d{4})/);<br/>
USNumber = "(" + USNumber[1] + ") " + USNumber[2] + "-" + USNumber[3];



回答3:


Use phone number masking plugins for that.

Check the following plugins:

  • http://wiki.jqueryui.com/w/page/12137996/Mask

  • http://igorescobar.github.io/jQuery-Mask-Plugin/

  • http://digitalbush.com/projects/masked-input-plugin/




回答4:


You can use my package https://github.com/jsonmaur/coverup, which can mask the input string onblur and maintain the symbols in the string.



来源:https://stackoverflow.com/questions/17651207/mask-us-phone-number-string-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!