rasilvap
rasilvap

Reputation: 2149

Javascript extract numbers and operators from string with negative values

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?

Upvotes: 0

Views: 465

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

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

Upvotes: 2

Related Questions