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

前端 未结 3 645
小蘑菇
小蘑菇 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 17:59

    The approach given in the accepted answer is concise and solid, but it has a drawback: if there's a big string with a lot of appearances of the given substring, it will be scanned till the end - even if one has to replace only at the beginning. The alternative would be using 'exec', then breaking off the chain right after the replacement is done:

    function replaceNthOccurence(source, pattern, replacement, n) {
      var substr = '';
      while (substr = pattern.exec(source)) {
        if (--n === 0) {
          source = source.slice(0, substr.index) + replacement + source.slice(pattern.lastIndex);
          break;
        }
      }
      return source;
    }
    
    console.log( replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '1st', 1) );
    console.log( replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '2nd', 2) );
    console.log( replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '3rd', 3) );

提交回复
热议问题