【问题标题】:jquery add dash between characters if length is greater than x如果长度大于 x,jquery 在字符之间添加破折号
【发布时间】:2017-06-08 03:26:01
【问题描述】:

我正在尝试在用户键入时格式化美国邮政编码,如果用户键入超过 5 个,则需要在第 5 个和第 6 个字符之间添加一个破折号,以便邮政编码的格式类似于

55555 或 55555-5555

我现在添加了一个破折号,但不管是否添加了第 6 个数字

//zip code formatting
$(".zip-val").keyup(function() {
    if($(this).val().length == 5) {
        $(this).val($(this).val() + "-");
    }
});

【问题讨论】:

标签: javascript jquery


【解决方案1】:

这个怎么样?

//zip code formatting
$(".zip-val").keyup(function() {
    zipcode = $(this).val();
    zipcode = zipcode.replace(/-/g, '');      // remove all occurrences of '-'

    if(zipcode.length > 5) {
        $(this).val(zipcode.substring(0, 5) + "-" + zipcode.substring(5));
    }
});

【讨论】:

    【解决方案2】:

    可以试试这个,拆分它并保留数字组,然后用格式重新创建字符串。如果您不是 5 人一组,这甚至会删除 -。

    您也可以修改它以适应信用卡号码系统。

    //zip code formatting
    $(".zip-val").keyup(function() {
        let val = $(this).val();
        if(val.length > 5) {
            let digits = val.split(/(\d{1,5})/);
            let str = "";
            for (let group of digits)
            {
              if (/^\d+$/.test(group))
              {
                str += group + "-";
              }
            }
            str = str.substring(0, str.length - 1);
            $(this).val(str);
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" class="zip-val" />

    【讨论】:

      【解决方案3】:

      您应该检查length 是否为6。另外,您可以添加更多检查,如果用户在第 6 个字符上使用 退格,它也会删除 '-' 字符

      $(".zip-val").keyup(function(e) {
          if(e.keyCode == 8)
          {
              if($(this).val().length == 6){
              var newText = $(this).val().substring(0 , 5);
              $(this).val(newText);
            }
          }
          else if($(this).val().length == 6) {
              var newText = $(this).val().substring(0 , 5) + '-' + $(this).val().substring(5);
              $(this).val(newText);
          }
      });
      

      演示:https://jsfiddle.net/sn5ghvb8/

      【讨论】:

        【解决方案4】:

        你可以试试这个。

        $(".zip-val").keyup(function() {
            if($(this).val().length > 5 ) {
                res = $(this).val().split("");//convert string to array
               if(jQuery.inArray( "-", res )){//checks if dash exist
               for (var i=res.length-1; i>=0; i--) {//removes dashes
                  if (res[i] === '-') {
                      res.splice(i, 1);
                      }
                    }
                    res.splice(5, 0, "-");    
                }
                $(this).val(res.join(''));
            }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-15
          • 2011-08-28
          • 2018-05-16
          • 1970-01-01
          • 2015-09-19
          相关资源
          最近更新 更多