Reputation: 352
I want to split an expression like -1*-0.8/5-5
into [ '-1', '*', '-0.8', '/', '5', '-', '5' ]
[ '-1', '*', '-0.8', '/', '5-5' ]
This is what I'm getting right now with expression.split(/([*/])/g);
Any suggestions on this?
Upvotes: 2
Views: 721
Reputation: 18279
Here is a solution. It correctly detects +
, -
, /
, *
and accept the use of whitespaces:
([*\/]|\b\s*-|\b\s*\+)
var expression = "-1*-0.8/5-5";
console.log(expression.split(/([*\/]|\b\s*-|\b\s*\+)/g));
From Wiktor's comment, here is an improvement accepting parenthesis
var expression = "-1 * -0.8 / (5 - 5)";
console.log(expression.split(/([*\/()]|\b\s*[-+])/g));
Upvotes: 4