jquery& regex的电话号码格式
问题描述:
我需要验证任何输入值并将其转换为电话号码格式,即
i need to verify and convert any input val into telephone number format, i.e
输入 er + f375g25123435s67 我需要将其转换为 +375 25 1234567
input er+f375g25123435s67 i need to convert into +375 25 1234567
..
keyup: function(){
newval = $(this).val().replace(/(\D+|\+)/g, '');
newval = newval.replace(/\d(?=(?:\d{3})+(?!\d))/g, '$& ');
$(this).val(newval);
}
..
这是另一个代码,我需要对其进行修改.
this is another code, i need to modify it..
答
要删除与手机无关的字符:
To strip out non-phone related characters:
var phone = "er+f375g25123435s67";
phone = phone.replace(/[^+|\d]/g, ""); // result = "+3752512343567"
然后匹配电话模式:
if (phone.match(/^[+][0-9]{12}$/)) // or /^[+][0-9]{13}$/ for 13 digits
...
编辑:这是我为测试&替换:
EDIT: Here's what I was able to come up with for the test & replace:
phone = $(this).val().replace(/^[^+]{1}/, '');
if (phone.length > 1)
phone = phone.substring(0,1) + phone.substring(1).replace(/[^\d]/g, '');
if (phone.match(/^[+][\d]{12}$/))
phone = phone.substring(0,4) + " " + phone.substring(4,6) + " " + phone.substring(6,14);