0

I have the next input: 8+9

I wold like to extract the numbers and the operators in separate arrays, I have the next code:

const numbers = input.split(/\D/g).filter(Boolean);
console.log("numbersBeforeFilter:", numbers);
const op = input.split(/\d/g).filter(Boolean);

in numbers I have ["8", "9"]

And in operators: ["+"]

Which it's ok, but if I have for example the next expression: -7, I have the next result:

in numbers I have ["7"]

And in operators: ["-"]

Which is wrong because I must have -7 in the numbers array and the operator one empty.

Any ideas?

1 Answer 1

2

You can match a number including a leading - if the token is preceded by either the start of the string, or by another operator:

const parse = str => str.match(/(?<=^|[-+*/])\-\d+|\d+|[-+*/]/g);
console.log(
  parse('8+9'),
  parse('-7'),
  parse('3*-5')
);

  • (?<=^|[-+*/])\-\d+ - Match a dash and digits preceded by
    • ^ - start of string, or by
    • [-+*/] - any of the characters -+*/
  • \d+ - Or match digits
  • [-+*/] - Or match operators
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.