我正在尝试在用户输入时格式化美国邮政编码,如果用户输入超过 5 个字符,则需要在第 5 个和第 6 个字符之间添加破折号,因此邮政编码的格式如下
55555 或 55555-5555
我现在添加了一个破折号,但无论是否添加第 6 个数字
//zip code formatting
$(".zip-val").keyup(function() {
if($(this).val().length == 5) {
$(this).val($(this).val() + "-");
}
});
最佳答案
这个怎么样?
//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));
}
});
关于javascript - jquery 如果长度大于 x,则在字符之间添加破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44426131/