Reputation: 25
I am trying to check if there is already decimal place after the last operator used in a mathematic expression. Since the expression can change, the final operator can be different.
if (val === "." && result.includes('.', result.lastIndexOf('+' || '-' || '/' || '*'))) {
setResult(result)
}
This is supposed to check if the current button pressed (val) is a decimal and if the current expression (result) already includes a decimal after the last operator, then to not add in a second decimal.
result.lastIndexOf('+' || '-' || '/' || '*')
This code currently only works for the + operator and does not look at the other 3 operators, -, /, & *. How would you have lastIndexOf look at the actual final operator used?
For example if the expression was 4+5-3, the above code returns the + before the 5 as the final operator used and not the - before the 3
Upvotes: 1
Views: 1062
Reputation: 7618
Might be overkill, but you can also use regular expression
let regex = /(?:\+|\-|\*|\/)(?!.*(?:\+|\-|\*|\/))/;
console.log(regex.exec("4+5-3").index);
console.log(regex.exec("1+2-3*4/5").index);
You can even integrate your goal to the regular expression. This example checks if there is a .
after the last +,-,*,/:
function canAppendDot(expression)
{
return !/(?:\.)(?!.*(?:\+|\-|\*|\/))/.test(expression)
}
console.log(canAppendDot("4+5.5-"));
console.log(canAppendDot("4+5.5-6"));
console.log(canAppendDot("4+5.5-6."));
console.log(canAppendDot("4+5.5-6.5"));
Upvotes: 1
Reputation: 19986
You could tweek lastIndexOf
a littlebit to achive your target. lastIndexOf
returns the index of the last occurance of a character in a string. Since you have to mach multiple operators, you can use the below logic
['+', '-', '*', '/']
list.Math.max
.const result = "15.36+30-5";
const characterList = ['+', '-', '*', '/'];
const indexList = characterList.map(character => result.lastIndexOf(character));
console.log(`Last index ${Math.max(...indexList)}`);
Upvotes: 1