gpt4 book ai didi

javascript - 用句点格式化输入字段

转载 作者:行者123 更新时间:2023-11-29 17:41:11 24 4
gpt4 key购买 nike

我正在尝试格式化字段,以便将输入到 input 中的整数预格式化为特定格式。

目前我有包含的 JQuery,它将输入的字符串格式化为 xx.xx.xx.xx,我如何强制格式为 x.xx.xx.xxx 并添加 8 个整数的限制?

$('.versionNum').keyup(function() {
var foo = $(this).val().split(".").join(""); // remove periods
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,2}', 'g')).join(".");
}
$(this).val(foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="versionNum" />

最佳答案

我不认为使用正则表达式构造输出是最易读的选择 - 它会有点复杂且难以阅读。相反,一旦您有了一串数字,切片您需要的每个部分,然后按 bool 值过滤(以删除空字符串)并按点连接:

$('.versionNum').keyup(function() {
const nums = $(this).val().replace(/\D/g, '');
const n0 = nums[0];
const n1 = nums.slice(1, 3);
const n2 = nums.slice(3, 5);
const n3 = nums.slice(5, 8);
$(this).val(
[n0, n1, n2, n3].filter(Boolean).join('.')
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="versionNum" />

正则表达式版本:

$('.versionNum').keyup(function() {
const numStr = $(this).val().replace(/\D/g, '');
const [, ...arr] = numStr.match(/(\d?)(\d{0,2})(\d{0,2})(\d{0,3})/);
$(this).val(
arr.filter(Boolean).join('.')
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="versionNum" />

关于javascript - 用句点格式化输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53076042/

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