Replace nth occurrence of string

前端 未结 3 1240
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  天涯浪人
    2021-01-14 01:48

    Use Avinash's approach with RegExp constructor

    const replace_nth = function (s, f, r, n) {
        // From the given string s, replace f with r of nth occurrence
        return s.replace(RegExp("^(?:.*?" + f + "){" + n + "}"), x => x.replace(RegExp(f + "$"), r));
    };
    

    Here's an example outout.

    $node
    Welcome to Node.js v13.1.0.
    Type ".help" for more information.
    >
    >  const replace_nth = function (s, f, r, n) {
    ...    // From the given string s, replace f with r of nth occurrence
    ...    return s.replace(RegExp("^(?:.*?" + f + "){" + n + "}"), x => x.replace(RegExp(f + "$"), r));
    ...};
    
    > replace_nth('hello world', 'l', 'L', 1)
    'heLlo world'
    

提交回复
热议问题