使用JS实现点作为千位分隔符时出现多余分隔符问题求助
千位分隔符格式化异常修复方案
问题根因
- 函数名不匹配:你定义的格式化函数名为
numberDots,但输入框事件里调用的是numberWithDots,名称不一致会导致调用逻辑异常。 - 未过滤非数字字符:实时输入场景下,每次触发keyup时输入框的值已经是上一次格式化后带点的内容,直接传入函数处理时,字符串里的点会干扰正则的数字计数逻辑,导致分隔符添加位置错乱。
修复代码
JavaScript函数
function numberWithDots(x) { // 先移除所有非数字字符,仅保留纯数字内容 const pureNum = x.toString().replace(/[^0-9]/g, ''); // 对纯数字做千位分隔格式化 return pureNum.replace(/\B(?=(\d{3})+(?!\d))/g, "."); }
HTML输入框
<div class="form-group"> <input type="text" asp-for="inputfield" class="form-control text-right" onkeyup="this.value=numberWithDots(this.value);"/> <span asp-validation-for="inputfield" class="text-danger"></span> </div>
可选优化(解决光标跳转问题)
如果需要避免修改输入值时光标自动跳到末尾的问题,可以添加光标位置记录逻辑:
function numberWithDots(input) { const start = input.selectionStart; const originLength = input.value.length; // 先移除所有非数字字符,仅保留纯数字内容 const pureNum = input.value.toString().replace(/[^0-9]/g, ''); // 对纯数字做千位分隔格式化 const formatted = pureNum.replace(/\B(?=(\d{3})+(?!\d))/g, "."); input.value = formatted; // 计算新的光标位置 const newLength = formatted.length; input.selectionStart = input.selectionEnd = start + (newLength - originLength); }
HTML部分修改为传元素本身:
<input type="text" asp-for="inputfield" class="form-control text-right" onkeyup="numberWithDots(this);"/>
内容的提问来源于stack exchange,提问作者Violeta
相关产品推荐
相关产品推荐

