Blistighast
Blistighast

Reputation: 25

How to find the lastIndexOf for multiple characters?

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

Answers (2)

Ricky Mo
Ricky Mo

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

Nitheesh
Nitheesh

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

  • Generate the list of characters that you need to check the last index. Here I have used ['+', '-', '*', '/'] list.
  • Run a map function against ths list and generate the array of last ndices of each operator.
  • Find the Maximum values from the generated array with some logic. I have mad use of Math.max.
  • The maximum in this list will be the last index of the list of operators that you wish to find from the expression.

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

Related Questions