如何正确使用此代码将所有出现的一个以上的十进制元素替换为一个



我在ReactJs中构建了一个计算器。我想防止用户输入多个十进制元素,例如2..3。任何时候用户这样做,我都想用一个十进制元素替换所有的十进制元素。因此2..3将成为2.3

这就是我试图实现这一目标的方式,但它不起作用

if (calc.input.match(/.{2,}/g)) {
setCalc(calc.input.replace(/.{2,}/g, "."));
}

setCalc是我用来改变状态的钩子。

这应该会有所帮助。如果我们在按键时已经在字符串中找到了小数,那么它基本上可以防止输入发生。

const text = document.querySelector('input[type="text"]');
text.addEventListener('keypress', e => {
// if the text already includes a decimal, and our current key is a decimal, prevent the new key from being added.
if (text.value.includes('.') && e.key == '.') e.preventDefault();
});
<input type="text">

记住字符串是不可变的,因此要更改calc.input的值,我必须将其重新分配给它自己。因此,对于这个特定的用例,这种方法对我有效。

请注意,它不会阻止以9.9.9形式输入

if (calc.input.match(/.{2,}/g)) {
setCalc(calc.input = calc.input.replace(/.{2,}/g, "."));
}

试试这个。。。

var S='456...........876';
S=S.replace(/.+/g,'.');  // I escape the period with a slash and place the + next to it to mean "all".
document.write(S);

最新更新