我需要允许用户输入必须以国家/地区代码开头的电话号码
所以它只能 +41 ...或0041 ... (41只是示例不固定)
如果用户输入无效号码 41 555 666
现在,用户也可以输入 + 41 / 555-666 ,因为我不想要其他字符我想删除它们只能获得 +41555666 波纹管。
因为我想简化一些事情我不想阻止 + 并用 00 替换它,所以如果用户输入 +41 88 / 555- 666 它代码应该将其修复为 004188555666 我认为这更容易。
但是我被卡住了我无法用 00 取代 + 所以我需要一些帮助,因为这可能需要regex
我不喜欢不知道:(非常好。
<input type="text" id="txt" onblur="
var t = document.getElementById('txt').value;
if(t.charAt(0) == '+'){t = t.replaceAt(0, '00');}
t = t.replace(/\D/g,'');document.getElementById('txt').value = t;"/>
答案 0 :(得分:1)
我不熟悉您示例中的电话号码格式,但这应该是正确的。
var phone = '+41/555-666';
var phone = phone.match(/\+?(\d{2})[^\d]?(\d{3})[^\d]?(\d{3})/);
//now you can format the phone number however you want!
var formatted = '00'+phone[1]+phone[2]+phone[3];
console.log(formatted);
如果作为变量传递,这就是正则表达式的样子 - 这对于分解和评论它是很好的。
var regex = new RegExp(
'\\+?'+ //optional "+"
'(\\d{2})'+ //capture 2 digits
'[^\\d]?'+ //optional character that isn't a digit
'(\\d{3})'+ //capture 3 digits
'[^\\d]?'+ //optional character that isn't a digit
'(\\d{3})' //capture 3 digits
);
var phone = '+41 88/555-666';
var regex = new RegExp(
'\\+?'+ //optional "+"
'(\\d{2})'+ //capture 2 digits
'[^\\d]?'+ //optional character that isn't a digit
'(\\d{2})?'+ //capture 2 optional digits
'[^\\d]?'+ //optional character that isn't a digit
'(\\d{3})'+ //capture 3 digits
'[^\\d]?'+ //optional character that isn't a digit
'(\\d{3})' //capture 3 digits
);
var phone = phone.match(regex);
for (var k in phone) {
//filter out the optional digit capture group if they don't exist
if (phone[k] === undefined) { phone[k] = ''; }
}
//now you can format the phone number however you want!
var formatted = '00'+phone[1]+phone[2]+phone[3]+phone[4];
console.log(formatted);
//some samples
var phone = '100-555-1234';
//var phone = '1234567890';
//var phone = '556.555.1234';
var phone = phone.match(/(\d{3})[^\d]?(\d{3})[^\d]?(\d{4})/);
var formatted = '('+phone[1]+') '+phone[2]+'-'+phone[3];
console.log(formatted);
答案 1 :(得分:0)
应该是
t=t.replace(/\+/,"00");