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?
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?
Share Improve this question edited Oct 22, 2013 at 19:52 LorenzoDonati4Ukraine-OnStrike 7,0154 gold badges39 silver badges58 bronze badges asked Sep 8, 2013 at 21:58 techdogtechdog 1,4914 gold badges19 silver badges39 bronze badges 1-
3
Use capturing parentheses in your regex and the delimiters end up in the array returned by
.split()
. (According to MDN not all browsers support this, but I believe the major ones do?) – nnnnnn Commented Sep 8, 2013 at 22:07
2 Answers
Reset to default 5Expanding 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
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