Kostadin Kostadin - 1 day ago 4
Javascript Question

How remove non consecutive substrings in javascript

I' am trying to figure out how to find and delete a sub-string from a main string in javascript. For example I have the string "|1|2|3|4|5|" and I want to delete random sub-strings from this one. I made it work when i have consecutive sub-strings lets say "|1|2|", but I cant figure it out how to delete the non- consecutive sub- strings like "|1|4|". If you could help i would appropriate it.

Answer

you can try with regex replace,

"|1|2|3|4|5|".replace(/\|(1|4)\|/g,"|")

you get,

"|2|3|5|"

or better,

function replace_non_consecutives(s, subs){
    var v = subs.match(/[^|]+/g);
    var strregex = "\\|(" + v.join("|") + ")\\|";
    var re = new RegExp(strregex,"g");
    while ( s.match(re) ) s = s.replace(re,"|");
    return s;
}

replace_non_consecutives("|1|2|3|4|5|", "|1|2|4|");

you get,

"|3|5|" 
Comments