Replacing the nth instance of a regex match in Javascript

前端 未结 3 2095
旧巷少年郎
旧巷少年郎 2020-11-27 06:22

I\'m trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have

3条回答
  •  遥遥无期
    2020-11-27 06:55

    function pipe_replace(str,n) {
        m = 0;
        return str.replace(/\|\|/g, function (x) {
            //was n++ should have been m++
            m++;
            if (n==m) {
                return "&&";
            } else {
                return x;
            }
        });
    }
    

提交回复
热议问题