Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace nth occurrence of string

For example:

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

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

Like this: enter image description here

like image 789
ChenLee Avatar asked Feb 19 '16 07:02

ChenLee


2 Answers

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")}))
like image 89
Avinash Raj Avatar answered Nov 08 '22 17:11

Avinash Raj


Make a function like this using RegExp module

const replace_nth = function (s, f, r, n) {
    // From the given string s, find f, replace as r only on n’th 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'
like image 28
nehem Avatar answered Nov 08 '22 17:11

nehem