簡體   English   中英

如何使用JavaScript和jQuery替換正則表達式來格式化輸入字段?

[英]How do I format my input field using replace regex with javascript and jQuery?

我想設置<input id="phone_number" type="tel" name="phone_number" maxlength="14">格式,使其具有這樣的值(123) 456-7890

我當前的jQuery代碼:

jQuery("#phone_number").on("keypress", function(event) {
    var phoneReg = /[0-9]/g;
    var phoneKey = String.fromCharCode(event.keyCode);
    if(!phoneReg.test(phoneKey)){
        // dont display characters
        return false;
    } else {
        // display numbers only
        var phoneNumberVal = jQuery("#phone_number").val();
        var phoneNumberUsFormat = phoneNumberVal.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
        jQuery("#phone_number").val(phoneNumberUsFormat);
    }
});

上面的代碼只能after鍵入所有數字after才能格式化電話號碼: (123) 456-7890

我想發生的是,當用戶到達第3rd位和6th位時,開始添加parenthesesdash

我目前正在嘗試的是:

jQuery("#phone_number").on("keypress", function(event) {
    var phoneReg = /[0-9]/g;
    var phoneKey = String.fromCharCode(event.keyCode);
    if(!phoneReg.test(phoneKey)){
        // dont display characters
        return false;
    } else {
        // display numbers only
        if(phoneNumberVal.length < 4) {
            newNumber  = phoneNumberVal.replace(/(\d{3})/,"($1) ");
            jQuery("#phone_number").val(newNumber);
        }
    }
});

上面更新的代碼的問題是無法檢測到6th位數字,然后自動添加-

任何幫助是極大的贊賞。 謝謝

我建議您遵循以下過程:

  • 如果當前輸入的值與(XXX) XXX-XXXX格式不對應,則僅檢查數字位數。
    • 如果(XXX) XXX- 6(= XXXXXX... ),則轉換為(XXX) XXX- ,如果存在,則轉換為其余部分。
    • 否則,如果在3和6之間(= XXX... )之間,則轉換為(XXX)加上其余的數字(如果有的話)(請注意我所寫格式的最后一個空格)。
    • 然后更新輸入的值。
  • 否則,如果顯示的格式正確,請避免鍵入更多字符的可能性。

下面的代碼段(有一些好處):

 $('#telephone').on('keyup', function(e) { // If not removing a character... // (Without that check, you'll not be able to remove characters correctly.) if (e.key !== 'Backspace') { let value = $(this).val(); // If the value is not corresponding to wanted format... if (!/\\(\\d{3}\\) \\d{3}-\\d{4}/.test(value)) { // Only keeps digits. value = value.replace(/[^\\d]/g, ''); // If we have at least 6 digits, converts the value to "(XXX) XXX-...". if (value.length >= 6) { value = `(${value.substring(0, 3)}) ${value.substring(3, 6)}-${value.substring(6)}`; } // If we have at least 3 digits (but less than 6), converts the value to "(XXX) ...". else if (value.length >= 3) { value = `(${value.substring(0, 3)}) ${value.substring(3)}`; } // Updates the input's value. $(this).val(value); } // If the format is correct, just avoid to have too much characters. else { $(this).val(value.substring(0, 14)); } } }); // Doesn't display unwanted characters. // (Did this on a different event. Try replacing "input" by "keyup" to see why.) $('#telephone').on('input', function() {$(this).val($(this).val().replace(/[^\\d() -]/g, ''));}); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="telephone"> 

在第6個字符之后嘗試類似的方法?

 $("input[name='phone']").keyup(function() { $(this).val($(this).val().replace(/^(\\d{3})(\\d{3})(\\d)+$/, "($1)$2-$3")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input name="phone" maxlength="14" /> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM