繁体   English   中英

jquery&regex的电话号码格式

[英]telephone number format with jquery&regex

我需要验证并将任何输入值转换为电话号码格式,即

输入er + f375g25123435s67我需要转换为+375 25 1234567

..

keyup: function(){
newval = $(this).val().replace(/(\D+|\+)/g, '');
newval = newval.replace(/\d(?=(?:\d{3})+(?!\d))/g, '$& ');
$(this).val(newval);
}

..

这是另一个代码,我需要修改它..

删除非电话相关字符:

var phone = "er+f375g25123435s67";
phone = phone.replace(/[^+|\d]/g, "");  // result = "+3752512343567"

然后匹配手机模式:

if (phone.match(/^[+][0-9]{12}$/)) // or /^[+][0-9]{13}$/ for 13 digits
    ...

编辑 :这是我能够为测试和替换提出的:

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

位于: http//jsfiddle.net/cabbott/KaYeJ/

你可以试试这个:

//这将删除非数字

keyup:function(){

var phone = $(this).val()。replace(/ \\ D / g,'');
var myRegexp = /(\\ d {3})(\\ d {3})(\\ d *)/ g

var match = myRegexp.exec(phone); $(this).val('+'+ match [1] +''+ match [2] +''+ match [3]);

 } 

$ 1 $ 2和$ 3应为375 25 1234567

评论:抱歉,不知道你想要一个完整的代码答案。 http://jsfiddle.net/UcJeV/4/

$('input').live({   
    keyup: function() {           
        var ipt = $(this).val().replace(/[^\d]*/g, ""); // remove non-digits

        ipt = ipt.replace(/(\d{1,3})(\d{1,2})?(\d{1,7})?.*/g, '+$1 $2 $3');

        $(this).val(ipt);       
    }
});

小提琴测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM