在键盘输入时,在每n个字符后加上短划线

Bro*_*val 0 javascript regex jquery

$('.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);
});
Run Code Online (Sandbox Code Playgroud)

我发现这个教程将破折号每4个字符之后,从这里我的问题是什么,如果字符间隔不固定就像这个例子只每4什么如果间隔之后是3 characters "-" 2 characters "-" 4 characters "-" 3 characters "-"这样它会出现这样的123-12-1234-123-123.

nha*_*tdh 8

在这种情况下,只需编写正常代码来解决问题就更方便了:

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;
}
Run Code Online (Sandbox Code Playgroud)

样品用法:

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);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="creditCardText" />
Run Code Online (Sandbox Code Playgroud)

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