gpt4 book ai didi

javascript - 我如何将字符串限制为仅 12 个字符

转载 作者:行者123 更新时间:2023-11-28 04:00:31 25 4
gpt4 key购买 nike

我有一个向电话号码字段添加破折号的函数,我如何将此字段中的字符限制为仅 12 个字符?

function dash(el, after) {
after = after || 3;
var v = el.value.replace(/[^\dA-Z]/g, ''),
reg = new RegExp(".{" + after + "}", "g")
el.value = v.replace(reg, function(a, b, c) {
return a + '-';
});
}

var el = document.getElementById('phone');
el.addEventListener('keyup', function() {
if (el.value.length <= 8) {
dash(this, 3);
} else {
el.value.length++;
}
if (el.value.length >= 12) {
el.value.length = el.substring(0, 12);
}
});
<span>Phone</span><input id="phone" class="comInputc" name="phone" type="text">

最佳答案

最简单的方法是使用 HTML maxlength属性:

<span>Phone</span><input id="phone" class="comInputc" name="phone" type="text" maxlength="12">

关于javascript - 我如何将字符串限制为仅 12 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53897473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com