问题描述
我需要定期发送美国电话号码格式。我想用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屏蔽美国电话号码字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!