Replace nth match of matches with regex

前端 未结 2 1789
一个人的身影
一个人的身影 2020-12-19 20:24

I\'m trying to find a way to replace nth match of more matches lite this.

string = \"one two three one one\"

How do I target the se

相关标签:
2条回答
  • 2020-12-19 20:48

    Update :

    To make it dynamic use this:

    ((?:.*?one.*?){1}.*?)one
    

    where the value 1 means (n-1); which in your case is n=2

    and replace by:

    $1\(one\)
    

    Regex101 Demo

    const regex = /((?:.*?one.*?){1}.*?)one/m;
    const str = `one two three one one asdfasdf one asdfasdf sdf one`;
    const subst = `$1\(one\)`;
    const result = str.replace(regex, subst);
    console.log( result);

    0 讨论(0)
  • 2020-12-19 20:53

    A more general approach would be to use the replacer function.

    // Replace the n-th occurrence of "re" in "input" using "transform"
    function replaceNth(input, re, n, transform) {
      let count = 0;
    
      return input.replace(
        re, 
        match => n(++count) ? transform(match) : match);
    }
    
    console.log(replaceNth(
      "one two three one one", 
      /\bone\b/gi,
      count => count ===2,
      str => `(${str})`
    ));
    
    // Capitalize even-numbered words.
    console.log(replaceNth(
      "Now is the time",
      /\w+/g,
      count => !(count % 2),
      str => str.toUpperCase()));

    0 讨论(0)
提交回复
热议问题