如何解决我如何正确使用此代码将所有出现的一个以上十进制元素替换为一个?
我在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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。