Kostadin Kostadin - 1 year ago 80
Javascript Question

Finding 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 Source

you can try with regex replace,


you get,


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,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download