在键盘输入过程中,每n个字符后加一个破折号 [英] put dash after every n character during input from keyboard

查看:110
本文介绍了在键盘输入过程中,每n个字符后加一个破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$('.creditCardText').keyup(function() {
  var foo = $(this).val().split("-").join(""); // remove hyphens
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
  }
  $(this).val(foo);
});

我发现本教程在此处的每4个字符后加破折号我的问题是,如果字符间隔不是恒定的(如本例中所示),则仅在每4个字符后出现一次,如果间隔为3 characters "-" 2 characters "-" 4 characters "-" 3 characters "-",那么它将显示为123-12-1234-123-123.

I found this tutorial on putting dash after every 4 character from here my question is what if the character interval is not constant like in this example it is only after every 4 what if the interval is 3 characters "-" 2 characters "-" 4 characters "-" 3 characters "-" so it would appear like this 123-12-1234-123-123.

推荐答案

在这种情况下,只需编写普通代码即可解决问题:

In this case, it is more convenient to just write normal code to solve the problem:

function format(input, format, sep) {
    var output = "";
    var idx = 0;
    for (var i = 0; i < format.length && idx < input.length; i++) {
        output += input.substr(idx, format[i]);
        if (idx + format[i] < input.length) output += sep;
        idx += format[i];
    }

    output += input.substr(idx);

    return output;
}

样品用量:

function format(input, format, sep) {
    var output = "";
    var idx = 0;
    for (var i = 0; i < format.length && idx < input.length; i++) {
        output += input.substr(idx, format[i]);
        if (idx + format[i] < input.length) output += sep;
        idx += format[i];
    }

    output += input.substr(idx);

    return output;
}

$('.creditCardText').keyup(function() {
    var foo = $(this).val().replace(/-/g, ""); // remove hyphens
    // You may want to remove all non-digits here
    // var foo = $(this).val().replace(/\D/g, "");

    if (foo.length > 0) {
        foo = format(foo, [3, 2, 4, 3, 3], "-");
    }
  
    
    $(this).val(foo);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="creditCardText" />

尽管可以使用正则表达式进行部分匹配和捕获,但必须使用替换功能来进行替换.在替换功能中,我们需要确定实际上有多少个捕获组捕获了一些文本.由于regex没有干净的解决方案,因此我编写了一个更通用的函数,如上所示.

While it is possible to do partial matching and capturing with regex, the replacement has to be done with a replacement function. In the replacment function, we need to determine how many capturing group actually captures some text. Since there is no clean solution with regex, I write a more general function as shown above.

这篇关于在键盘输入过程中,每n个字符后加一个破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆