Replace nth match of matches with regex

前端 未结 2 1796
一个人的身影
一个人的身影 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);

提交回复
热议问题