问题
I have an equation I want to split by using operators +
, -
, /
, *
as the delimiters. Then I want to change one item and put the equation back together. For example an equation could be
s="5*3+8-somevariablename/6";
I was thinking I could use regular expressions to break the equation apart.
re=/[\+|\-|\/|\*]/g
var elements=s.split(re);
Then I would change an element and put it back together. But I have no way to put it back together unless I can somehow keep track of each delimiter and when it was used. Is there another regexp tool for something like this?
回答1:
Expanding on nnnnn's post, this should work:
var s = '5*3+8-somevariablename/6';
var regex = /([\+\-\*\/])/;
var a = s.split(regex);
// iterate by twos (each other index)
for (var i = 0; i < a.length; i += 2) {
// modify a[i] here
a[i] += 'hi';
}
s = a.join(''); // put back together
回答2:
You can also generate regexp dynamically,
var s = '5*3+8-somevariablename/6';
var splitter = ['*','+','-','\\/'];
var splitted = s.split(new RegExp('('+splitter.join('|')+')'),'g'));
var joinAgain = a.join('');
Here splitted array holds all delimiters because of () given in RegExp
来源:https://stackoverflow.com/questions/18689045/split-equation-string-by-multiple-delimiters-in-javascript-and-keep-delimiters-t