split equation string by multiple delimiters in javascript and keep delimiters then put string back together

我与影子孤独终老i 提交于 2020-01-14 19:51:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!