Replacing the nth instance of a regex match in Javascript

前端 未结 3 2107
旧巷少年郎
旧巷少年郎 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 07:21

    here's something that works:

    "23||45||45||56||67".replace(/^((?:[0-9]+\|\|){n})([0-9]+)\|\|/,"$1$2&&")
    

    where n is the one less than the nth pipe, (of course you don't need that first subexpression if n = 0)

    And if you'd like a function to do this:

    function pipe_replace(str,n) {
       var RE = new RegExp("^((?:[0-9]+\\|\\|){" + (n-1) + "})([0-9]+)\|\|");
       return str.replace(RE,"$1$2&&");
    }
    

提交回复
热议问题