Home>

For example, I have a string likeresult='23+5*8-2'

The last operator can be anything in the form +,-,/,*;

My task is to find the last statement and separate the last number (in my example "2") from the rest of the expression ("23+5*8").

I understand that everything is tied up with regular expressions, but I'm not strong in them, and the deadlines are running out.

  • Answer # 1
    const regexp= /(\d+)[\+\-\/\*]{1}(\d+)[\+\-\/\*]{1}(\d+)[\ +\-\/\*]{1}(\d+)/g;
    const str= '23+5*8-2';
    const array= [...str.matchAll(regexp)];
    console log(array);
    

    Result:

    Array [Array ["23+5*8-2", "23", "5", "8", "2"]]
    
  • Answer # 2
    const regexp= /(\d+)[\+\-\/\*]{1}(\d+)[\+\-\/\*]{1}(\d+)[\ +\-\/\*]{1}(\d+)/g;
    const str= '23+5*8-2';
    const array= [...str.matchAll(regexp)];
    console log(array);
    

    Result:

    Array [Array ["23+5*8-2", "23", "5", "8", "2"]]