Skip to content Skip to sidebar Skip to footer

Split Equation String By Multiple Delimiters In Javascript And Keep Delimiters Then Put String Back Together

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

Solution 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

Solution 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

Post a Comment for "Split Equation String By Multiple Delimiters In Javascript And Keep Delimiters Then Put String Back Together"