使用JavaScript屏蔽美国电话号码字符串 [英] Mask US phone number string with JavaScript

查看:125
本文介绍了使用JavaScript屏蔽美国电话号码字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定期发送美国电话号码格式。我想用JavaScript将电话号码字符串替换为美国电话号码字符串格式。

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

任何人都可以在JavaScript中为我显示正则表达式吗?

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

推荐答案

这个答案假定您需要以下格式:(000)000-0000 (如OP所述) 。

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

有多种不同的方法可以实现这一点,但这里有几种不同的方法:

如果您想简单地屏蔽 blur 事件中的数字(当该字段损失<$ c $时) c>焦点),然后你可以使用以下内容:

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"/>

这篇关于使用JavaScript屏蔽美国电话号码字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆