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

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

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.

Share Improve this question asked Dec 28, 2014 at 8:48 Mohit PandeyMohit Pandey 3,8537 gold badges27 silver badges38 bronze badges 2
  • 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
Add a ment  | 

3 Answers 3

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

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信