简体   繁体   中英

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

I built a calculator in ReactJs. And i would like to prevent the user from entering more than one decimal element eg 2..3 Anytime a user does this i'd like to replace all the decimal elements with a single one. So 2..3 would become 2.3

This is how i am trying to achieve this but it doesnt work

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

setCalc is the hook i'm using to change state.

This should help. It basically keeps the input from happening if we already find a decimal in the string already when hitting a key.

 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">

Remembered that strings are immutable and so to change the value of calc.input I would have to reassign it to itself. And so this approach worked for me for this particular use case.

Note that it doesnt prevent input in the form 9.9.9

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

Try this...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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