簡體   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