$('.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);
});
我发现这个教程是关于在 here 每 4 个字符后添加破折号我的问题是,如果字符间隔不是恒定的,就像本例中那样,只有在每 4 个字符之后,如果间隔是 3 个字符“-” 2 个字符“-” 4 个字符“-” 3 个字符“-”
所以它看起来像这样 123-12-1234-123-123
。
最佳答案
这种情况下,直接编写普通代码来解决问题会更方便:
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" />
虽然可以使用正则表达式进行部分匹配和捕获,但必须使用替换函数来完成替换。在替换函数中,我们需要确定有多少个捕获组实际捕获了某些文本。由于正则表达式没有干净的解决方案,因此我编写了一个更通用的函数,如上所示。
关于javascript - 从键盘输入时,每 n 个字符后加破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852888/