Clay
Clay

Reputation: 65

Regular Expression to replace arithmetic operators in Javascript

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

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

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

Upvotes: 7

Related Questions