Reputation: 65
I have an array of string that contains arithmetic operators and I would like to replace those arithmetic operators in the array with a new arithmetic operator.
For instance:
var equation = '5.0 + 9.34 - 6.0 * 2.1 * 3.1 / 2.0';
var newEquation = equation.replace(/+-*//, '+');
However, it does not change to the wanted result. Please advise. Your contribution is much appreciated.
Upvotes: 1
Views: 5873
Reputation: 115222
var equation = '5.0 + 9.34 - 6.0 * 2.1 * 3.1 / 2.0';
var newEquation = equation.replace(/[+*\/-]/g, '+');
// or : equation.replace(/[+\-*/]/g, '+');
console.log(newEquation);
var equation = '-5.0 + 9.34 - 6.0 * -2.1 * 3.1 / -2.0';
var newEquation = equation.replace(/(?!^-)[+*\/-](\s?-)?/g, '+$1');
console.log(newEquation);
Upvotes: 7