首页 > 解决方案 > 输入小数时如何使用正则表达式保留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;">

标签: javascriptregex

解决方案


因此,您要修剪前导零,如果后跟小数点或字符串末尾,则保留一个前导零,并且您要修剪小数点后的尾随零。

您可以将非数字、非句点字符与:

[^\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');

推荐阅读