我正在使用 JavaScript 强制用户输入我希望的格式的值,
我使输入只能插入数字,并且它会在第 7 个位置自动添加 -
值。
但是我发现如果用户想输入000319-19-2939
,结果将变成319192-93-9
。
这个javascript当它与第一个一起出现时,将删除0
。
document.getElementById('others_textb').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,6})(\d{0,2})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : + x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
});
<input id="others_textb" type="text" name="number" placeholder="xxxxxx-xx-xxxx" >
我想要的是使 0
可以成为此输入中的第一个数字。
最佳答案
您通过+x[1]
将第一个匹配组强制为整数:
e.target.value = !x[2] ? x[1] : + x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
^
您可以删除强制转换 (+
),其余代码应保留前导零。
document.getElementById('others_textb').addEventListener('input', function(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,6})(\d{0,2})(\d{0,4})/);
e.target.value =
!x[2]
? x[1]
: x[1] + '-' + x[2] + (x[3]
? '-' + x[3]
: '');
});
<input id="others_textb" type="text" name="number" placeholder="xxxxxx-xx-xxxx">
关于javascript - 使用 JavaScript 替换和匹配方法时允许第一位数字为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49810461/