How to replace all BUT the first occurrence of a pattern in string

后端 未结 6 733
余生分开走
余生分开走 2020-12-03 07:04

quick question: my pattern is an svg string and it looks like l 5 0 l 0 10 l -5 0 l 0 -10 To do some unittest comparison against a reference I need to ditch all

6条回答
  •  悲&欢浪女
    2020-12-03 07:46

    There's no JS RegExp to replace everything-but-the-first-pattern-match. You can, however, implement this behaviour by passing a function as a second argument to the replacemethod.

    var regexp = /(foo bar )(red)/g; //Example
    var string = "somethingfoo bar red  foo bar red red pink   foo bar red red";
    var first = true;
    
    //The arguments of the function are similar to $0 $1 $2 $3 etc
    var fn_replaceBy = function(match, group1, group2){ //group in accordance with RE
        if (first) {
            first = false;
            return match;
        }
        // Else, deal with RegExp, for example:
        return group1 + group2.toUpperCase();
    }
    string = string.replace(regexp, fn_replaceBy);
    //equals string = "something foo bar red  foo bar RED red pink   foo bar RED red"
    

    The function (fn_replaceBy) is executed for each match. At the first match, the function immediately returns with the matched string (nothing happens), and a flag is set.
    Every other match will be replaced according to the logic as described in the function: Normally, you use $0 $1 $2, et cetera, to refer back to groups. In fn_replaceBy, the function arguments equal these: First argument = $0, second argument = $1, et cetera.

    The matched substring will be replaced by the return value of function fn_replaceBy. Using a function as a second parameter for replace allows very powerful applcations, such as an intelligent HTML parser.

    See also: MDN: String.replace > Specifying a function as a parameter

提交回复
热议问题