1

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.

1
  • That's not an array. It's just a string literal. Commented Jun 14, 2016 at 4:16

1 Answer 1

7

Use character class([])

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);


UPDATE : For avoiding negative numbers use negative look-ahead assertion and capturing group.

var equation = '-5.0 + 9.34 - 6.0 * -2.1 * 3.1 / -2.0';

var newEquation = equation.replace(/(?!^-)[+*\/-](\s?-)?/g, '+$1');

console.log(newEquation);

Regex explanation here

Regular expression visualization

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your contribution @Pranav Is there a way to differentiate from a negative number? For instance: '-5.0 + 9.34 - -6.0'
Thank you @Pranav. Much appreciated!
@Clay : glad to help :)

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.