javascript 如何在html输入中的四个字符后插入空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28779631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert space after four characters in html input?
提问by soniya soniya
I need to insert a space after every four characters while the user is typing a credit card number using JavaScript .
当用户使用 JavaScript 键入信用卡号时,我需要在每四个字符后插入一个空格。
<input type="text" size="19" maxlength="19" data-stripe="number" placeholder="1234 5678 9012 3456">
What is the best way to accomplish this ?
实现这一目标的最佳方法是什么?
采纳答案by marjes
回答by vaneayoung
try this:
试试这个:
input:
输入:
<input type="text" maxlength="19" class="text" />
jquery:
查询:
$('.text').on('keyup', function() {
var foo = $(this).val().split(" ").join("");
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join(" ");
}
$(this).val(foo);
});
fiddle: https://jsfiddle.net/juspC/126/
回答by pmrotule
I see that you are using Stripe. They offer a nice plugin that will do exactly what you are looking for. Note that you can use this plugin without using Stripe:
我看到您正在使用 Stripe。他们提供了一个很好的插件,可以完全满足您的需求。请注意,您可以在不使用 Stripe 的情况下使用此插件:
https://github.com/stripe/jquery.payment
https://github.com/stripe/jquery.payment
And if you are looking for a pure javascript and light version, I created one that will support the American Express format (15 digits) as well as Visa, MasterCard and others (16 digits):
如果您正在寻找纯 javascript 和轻量级版本,我创建了一个支持美国运通格式(15 位)以及 Visa、MasterCard 和其他(16 位)格式的版本:
https://stackoverflow.com/a/39804917/1895428
https://stackoverflow.com/a/39804917/1895428
Watch out for the simple solutions that will replace the whole value and always put the focus at the end of the input: it can be annoying if the user edits what he previously entered.
注意将替换整个值并始终将焦点放在输入末尾的简单解决方案:如果用户编辑他之前输入的内容可能会很烦人。