简体   繁体   中英

jHow to replace string from a part of given string?

var ans = '#1>2,2,2,0,#2>3,2,1'

I want remove all 2 immediate after #1> but not #2>. My expected result is:

ans = '#1>0,#2>3,2,1'

how can I do this using jquery?

Try this one

var ans = '#1>2,2,2,0,#2>3,2,1'

ans.replace(/#1>(2,{0,})+/g,function() {
    return "#1>"
})

output:

#1>0,#2>3,2,1

Test here

Here is a mix of regex replacement with recursion:

/**
 *  @param a - original string
 *  @param s - string to search for
 *  @param r - string to replace with
 */
function fun(a, s, r) {

   var re = new RegExp(s + ',?');

   // replace #1>2 with #1> and also the comma , if it is present
   a = a.replace(re, r);

   // if there are more such instances of #1>2 then call the function recursively
   if (a.indexOf(s) > -1) {
       a = fun(a, s, r);
   }
   return a;
}

and I tested on following values:

fun('#1>2,2,2,0,#2>3,2,1', '#1>2', '#1>')     // '#1>0,#2>3,2,1'
fun('#1>2,0,#2>3,2,1', '#1>2', '#1>')         // '#1>0,#2>3,2,1'
fun('#1>2,0,#2>3,2,1,#1>2', '#1>2', '#1>')    // '#1>0,#2>3,2,1,#1>'

You could also replace '#2>3' with '#2>'

fun('#1>2,0,#2>3,2,1,#1>2', '#2>3', '#2>')    // "#1>2,0,#2>2,1,#1>2"

Or, using a single regex (this doesn't support variable yet):

function fun(a) {
    return a.replace(/#1>(?:2,*)+/g, '#1>');
}

fun('#1>2,2,2,0,#2>3,2,1')     // '#1>0,#2>3,2,1'
fun('#1>2,0,#2>3,2,1')         // '#1>0,#2>3,2,1'
fun('#1>2,0,#2>3,2,1,#1>2')    // '#1>0,#2>3,2,1,#1>'

Of course regex is a working solution here. But for the ones who loves iterative solutions this is one of the ways to go.

function blah(ans) {
    var newAns = '';
    for (var i = 0; i < ans.length; i++) {
        var triplet = ans.substr(i, 3);
        if (triplet == '#1>') {
            newAns = newAns.concat(triplet);
            i += 3;

            while (ans.substr(i, 2) == '2,') {
                i += 2;
            }
        }
        newAns = newAns.concat(ans[i]);
    }

    return newAns;
}

var ans = blah('#1>2,2,2,0,#2>3,2,1');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM