For example:
'abcjkjokabckjk'.replace('/(abc)/g',...)
If I want to replace a specify position 'abc', what I can do?
Like this:
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")}))
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With