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, ' ');
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.
- think about negative numbers as well. – Braj Commented Dec 28, 2014 at 9:06
- Accepted @Amit answer because there is no -ve number in my case. Also, i only need to find out the number array. But it would be great if anyone can provide a solution with negative number as well. – Mohit Pandey Commented Dec 28, 2014 at 9:14
3 Answers
Reset to default 4-
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, ' ');
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'
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...
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745384581a4625380.html
评论列表(0条)