0

I don´t understand how this code works. How does it set the state using the regex? And most importantly, how does it know to set the state using the result variable?

handleClick(evt) {
    const id = evt.target.id;
    const result = evt.target.value;
this.setState(prevState => ({
        value: `${prevState.value}${result}`
          .replace(/([/+\-/*=])([/+\-*=])/g, "$2")
          .replace(/^0+(?=[1-9])/, "")
          .replace(/^0+(?=\.)/, "0")
          .replace(/^0+\B/, "")
      })); 
}

}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

0

So this code do the following:
1. Concatenate prevState.value and evt.target.value into single string (learn more about ES6 Template literals)
2. Replace all combinations like ++, +-, +*, +=, -+, --, -*, -=, *+, *-, **, *=, =+, =-, =*, == to it's second character (but I think there is error in the code, replace statement should be ([\+\-*=])([\+\-*=]), learn more about regex)
3. Remove from string all number, that start with 0, like 0009, 01, etc.
4. Remove all words, that start with 0, like 0a, 0000z, etc.
5. Remove all 0 from string (learn more about \B)
6. Set result string to the state.value (learn more about React setState())

Yura
  • 2,925
  • 2
  • 18
  • 27