Reputation: 3813
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
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
Reputation: 46841
Split based on operator that is in between digits for considering negative numbers as well.
(?!=\d) [-+*/] (?=\d|-)
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
Upvotes: 1
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