javascript - 输入小数时如何使用正则表达式保留0开始字符?
问题描述
我用这个代码替换非数字字符,当数字以0开头时,如“000001111”或“0000000”,0将被替换。“000001111”更改为“1111”,“0000000”更改为“0” .
但是当我输入一个小数时,想要这个。
例如,我输入“00012.340”,保持“12.34”,当我输入“00.00”时保持“0.0”,当我输入“000.0012”时保持“0.0012”。如何修复我的代码的 onkeyup?
我的代码:
<input id="text_target_value" maxlength="11" class="text-right number" type="text" onkeyup="value=value.replace(/[^\d]+|^0+(?!$)/g, '')" style="display: inline-block;">
解决方案
因此,您要修剪前导零,如果后跟小数点或字符串末尾,则保留一个前导零,并且您要修剪小数点后的尾随零。
您可以将非数字、非句点字符与:
[^\d.]
你可以匹配不受欢迎的前导零
^0+(?=0(\.|$)|\d)
换句话说,匹配前导零,后跟0.
,或0
字符串的结尾,或其他数字。
以上两种模式都可以用空字符串代替。
然后,要修剪尾随零,您必须捕获组中的小数点和小数位,然后匹配尾随零,并替换为第一个捕获的组:
document.querySelector('#text_target_value').onkeyup = function() {
this.value = this.value
.replace(/[^\d.]+|^0+(?=0(\.|$)|\d)/g, '')
// Still need to trim trailing zeros after decimal point:
.replace(/(\.\d*[1-9])0+$/, '$1');
}
<input id="text_target_value" maxlength="11" class="text-right number" type="text">
首先替换非数字和非句点可能更清楚,并保持前导零的正则表达式分开:
this.value = this.value
// Replace anything that isn't a digit or a period:
.replace(/[^\d.]+/g, '')
// Replace undesirable leading zeros:
.replace(/^0+(?=0(\.|$)|\d)/g, '')
// Still need to trim trailing zeros after decimal point:
.replace(/(\.\d*[1-9])0+$/, '$1');
推荐阅读
- local - 本地家庭执行重启 Google Nest 中心
- python - 如何使用 python 日志记录模块在 dictConfig 文件中设置自定义日志记录处理程序
- javascript - 在 Vue.js 的子组件中放置 Modals
- c# - 多对多关系和创建视图
- c# - 如何使用 Convert.ToInt32 在 C# 中构造三元表达式?
- javascript - 如何让我的应用程序显示错误消息而不是损坏的图像链接?
- c# - 解析 M3U 文件
- ios - Xcode 11 GM Seed 工具链无效
- xamarin.forms - 图片不适合 ImageButton
- python - 带有 aws-lambda 的 Django 调度程序