繁体   English   中英

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

[英]How do i properly use this code to replace all occurrences of more than one decimal element with a single one?

我在 ReactJs 中构建了一个计算器。 而且我想防止用户输入多个小数元素,例如2..3任何时候用户这样做我都想用一个小数元素替换所有小数元素。 所以2..3会变成2.3

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

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

setCalc是我用来更改 state 的钩子。

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

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM