用正则表达式替换 Javascript 中的算术运算符 [英] Regular Expression to replace arithmetic operators in Javascript
本文介绍了用正则表达式替换 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.
例如:
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.
推荐答案
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);
这篇关于用正则表达式替换 Javascript 中的算术运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文