我需要验证并将任何输入值转换为电话号码格式,即
输入 er + f375g25123435s67 我需要转换为 +375 25 1234567
最合适的代码是:
$('input').live({
keyup: function(){
ipt = $(this).val().replace(/[^\d]*/g, "");
// remove non-digits
ipt = "+" + ipt.substring(0, 3) + " " + ipt.substring(4, 6) + " " + ipt.substring(7, 14);
$(this).val(ipt);
}
});
但我无法在+375
1)如何在+375
2)如何将ipt.substring(0, 3) + " " + ipt.substring(4, 6) + " " + ipt.substring(7, 14)
转换为正则表达式?
这里有一个答案:http://jsfiddle.net/5UvJr/
答案 0 :(得分:2)
答案 1 :(得分:0)
子串索引是错误的,试试这个:
ipt = "+" + ipt.substring(0, 3) + " " + ipt.substring(3, 5) + " " + ipt.substring(5, 12);
答案 2 :(得分:0)
这是一个答案:http://jsfiddle.net/5UvJr/
$('input').live({
keyup: function(){
var phone = $(this).val().replace(/\D/g, '');
phone = phone.substring(0,12);
var myRegexp = /(\d{3})(\d{2})(\d*)/g
var mphone = myRegexp.exec(phone);
$(this).val('+' + mphone [1] + ' ' + mphone [2] + ' ' + mphone [3]);
}
});