For example:
\'abcjkjokabckjk\'.replace(\'/(abc)/g\',...)
If I want to replace a specify position \'abc\', what I can do?
Like this
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'