ChenLee
ChenLee

Reputation: 1499

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

Upvotes: 6

Views: 11558

Answers (4)

Display name
Display name

Reputation: 926

function replaceNth(
  string: string,
  from: string,
  to: string,
  n: number
): string {
  const pattern = RegExp(escapeRe(from));
  let nth = 0;
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const result = string.replace(pattern, function (match, i, original) {
    nth++;
    return nth === n ? to : match;
  });
  console.log(`${string} => ${result}`);
  return result;
}

Upvotes: 0

nehem
nehem

Reputation: 13642

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'

Upvotes: 3

Tushar
Tushar

Reputation: 87203

This can be done without RegEx.

String methods String#indexOf, String#lastIndexOf can be used with String#substring

var string = 'abcde|abcde|abcde|abcde',
  needle = 'abc',
  firstIndex = string.indexOf(needle),
  lastIndex = string.lastIndexOf(needle);

// ----------------------------------------------------------------
// Remove first occurence
var first = string.substring(0, firstIndex) + '***' + string.substring(firstIndex + needle.length);
document.getElementById('first').innerHTML = first;

// ----------------------------------------------------------------
// Remove last occurence
var last = string.substring(0, lastIndex) + '***' + string.substring(lastIndex + needle.length);
document.getElementById('last').innerHTML = last;

// ----------------------------------------------------------------
// Remove nth occurence
// For Demo: Remove 2nd occurence
var counter = 2, // zero-based index
  nThIndex = 0;

if (counter > 0) {
  while (counter--) {
    // Get the index of the next occurence
    nThIndex = string.indexOf(needle, nThIndex + needle.length);
  }
  
  // Here `nThIndex` will be the index of the nth occurence
}

var second = string.substring(0, nThIndex) + '***' + string.substring(nThIndex + needle.length);
document.getElementById('second').innerHTML = second;
table tr td:nth-child(2) {
  color: green;
}
td {
  padding: 15px;
}
<table border="1px">
  <tr>
    <td>After replacing <strong>first</strong> occurence:</td>
    <td id="first"></td>
  </tr>
  <tr>
    <td>After replacing <strong>last</strong> occurence:</td>
    <td id="last"></td>
  </tr>
  <tr>
    <td>After replacing <strong>2nd<sup>zero-based index</sup></strong> occurence:</td>
    <td id="second"></td>
  </tr>
</table>

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174696

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")}))

Upvotes: 8

Related Questions