Find and replace nth occurrence of [bracketed] expression in string

前端 未结 3 644
小蘑菇
小蘑菇 2020-12-03 17:25

I have a form where the name attributes get updated, but the problem is im using multidimensional values as follows:



        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 18:20

    Here is another possible solution. You can pass the string.replace function a function to determine what the replacement value should be. The function will be passed three arguments. The first argument is the matching text, the second argument is the position within the original string, and the third argument is the original string.

    The following example will replace the second "L" in "HELLO, WORLD" with "M".

    var s = "HELLO, WORLD!";
    var nth = 0;
    s = s.replace(/L/g, function (match, i, original) {
        nth++;
        return (nth === 2) ? "M" : match;
    });
    alert(s); // "HELMO, WORLD!";
    

    See MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

提交回复
热议问题