I keep having troubles with this, and I´m honestly at a loss now. I keep getting the following error “Line 17: Unnecessary escape character: / no-useless-escape” (twice) and , on top of that, I still have two issues I can´t solve: it still allows multiple leading zeros (for instance “0000000” instead of limiting it to “0”) and still allows multiple decimal points in one expression (for instance, “0.2.2.2.2” instead of limiting it to “0.2”). Any ideas on how to solve these issues? I´m getting a bit fed up.
EDIT: Fixed the error message, and the leading zeros problem by adding a new Regex. Only problem left are the decimal points now (" 11. When the decimal element is clicked, a “.” should append to the currently displayed value; two “.” in one number should not be accepted"). Any ideas on how to solve it?
class Calculator extends Component {
constructor(props) {
super(props);
this.state = {value:0}
this.handleClick = this.handleClick.bind(this);
}
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(/\.+/g,".")
}));
if(id==="clear"){
this.setState({value : 0})
}
else if(id==="equals"){
this.setState({value: math.eval(this.state.value)})
}
}
render() {
return(
<div id="container">
<Display value={this.state.value} />
<div>
<Button onClick={this.handleClick} id="one" value={'1'} />
<Button onClick={this.handleClick} id="two" value={'2'}/>
<Button onClick={this.handleClick} id="three" value={'3'} />
<Button onClick={this.handleClick} id="divide" value={'/'} />
</div>
<div>
<Button onClick={this.handleClick} id="four" value={'4'} />
<Button onClick={this.handleClick} id="five" value={'5'} />
<Button onClick={this.handleClick} id="six" value={'6'} />
<Button onClick={this.handleClick} id="add" value={'+'} />
</div>
<div>
<Button onClick={this.handleClick} id="seven" value={'7'} />
<Button onClick={this.handleClick} id="eight" value={'8'} />
<Button onClick={this.handleClick} id="nine" value={'9'} />
<Button onClick={this.handleClick} id="subtract" value={'-'} />
</div>
<div>
<Button onClick={this.handleClick} id="zero" value={'0'} />
<Button onClick={this.handleClick} id="decimal" value={'.'} />
<Button onClick={this.handleClick} id="equals" value={'='} />
<Button onClick={this.handleClick} id="multiply" value={'*'} />
</div>
<div>
<Button onClick={this.handleClick} id="clear" value={'clear'} />
</div>
</div>
)
}