Mohit Pandey
Mohit Pandey

Reputation: 3813

Regex - replace method to remove operator from string produce undesired result

I have a string in which i want to replace operator like (+, -, /, *), so that i am able to separate expressions.

var exp = '9 + 3 - 7 / 4 * 6.56';

// current output 9 3 7 4 6 56
// desired result 9 3 7 4 6.56
document.body.innerHTML = exp.replace(/ /g,'').replace(/[+-\/\*]/g, ' ');

But, replace() method returns an undesirable result.

Upvotes: 0

Views: 1937

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174696

You could reduce your code like,

exp.replace(/\s*[-+\/*]\s*/g, ' ');

In some cases unescaped hyphens - at the middle of character class would act like a range operator. So you need to escape the hyphen or you need to put it at the start or at the end of the character class.

Example:

> var exp = '9 + 3 - 7 / 4 * 6.56';
> exp.replace(/\s*[-+\/*]\s*/g, ' ');
'9 3 7 4 6.56'

If the input contain negative number , i assumed that it would like in the below format.

> var exp = '-9 + 3 - 7 / 4 * -6.56';
undefined
> exp.replace(/\s+[-+\/*]\s+/g, ' ');
'-9 3 7 4 -6.56'

Upvotes: 4

Braj
Braj

Reputation: 46841

Split based on operator that is in between digits for considering negative numbers as well.

(?!=\d) [-+*/] (?=\d|-)

DEMO

It uses Look Around to look behind and ahead for digit around operator.

It works for negative numbers as well for example -9 + 3 - 7 / 4 * 6.56

Find more...

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

- signifies a range in character-class in regex. Either put it at the beginning or at the end or escape it.

document.body.innerHTML = exp.replace(/ /g,'').replace(/[+\/*-]/g, ' ');

Upvotes: 4

Related Questions