繁体   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