Replace nth occurrence of string

前端 未结 3 1264
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 01:16

For example:

\'abcjkjokabckjk\'.replace(\'/(abc)/g\',...)

If I want to replace a specify position \'abc\', what I can do?

Like this

3条回答
  •  梦毁少年i
    2021-01-14 01:43

    Use RegExp constructor to pass variables inside regex.

    var s = 'abcjkjokabckjk'
    search = 'abc'
    var n = 2
    alert(s.replace(RegExp("^(?:.*?abc){" + n + "}"), function(x){return x.replace(RegExp(search + "$"), "HHHH")}))

提交回复
热议问题