3

This question been asked before, but I did not succeed in solving the problem. I have a string that contains numbers, e.g.

var stringWithNumbers = "bla_3_bla_14_bla_5";

I want to replace the nth occurence of a number (e.g. the 2nd) with javascript. I did not get farer than

var regex = new RegExp("([0-9]+)");
var replacement = "xy";
var changedString = stringWithNumbers.replace(regex, replacement);

This only changes the first number. It was suggested to use back references like $1, but this did not help me.

The result should, for example, be

"bla_3_bla_xy_bla_5" //changed 2nd occurence
tjons
  • 4,749
  • 5
  • 28
  • 36
AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120
  • Which nth are you looking to replace? – tjons Oct 17 '17 at 12:37
  • the second in my case, but I am looking for a general solution. – AGuyCalledGerald Oct 17 '17 at 12:38
  • please add a wanted result of the above replacement. – Nina Scholz Oct 17 '17 at 12:40
  • I removed the [How can I replace a match only at a certain position inside the string?](https://stackoverflow.com/questions/6843441/how-can-i-replace-a-match-only-at-a-certain-position-inside-the-string) close reason as it does not really pertain to the current problem. Actually, I had to change its title from *JavaScript: how can I replace only Nth match in the string?* as it is not about replacing an Nth *match* occurrence, but at a specified position inside the string. – Wiktor Stribiżew Oct 18 '17 at 08:35
  • `function replNth(str,n,find,repl){var A=str.split(find);return A.slice(0,n).join(find)+repl+A.slice(n).join(find)}`, used like `newString=replNth('bla_3_bla_14_bla_5', 2, 'bla', 'xy');`, produces result "bla_3_xy_14_bla_5". ([answer](https://stackoverflow.com/a/69278160/8112776)) – ashleedawg Sep 22 '21 at 04:28

2 Answers2

6

You may define a regex that matches all occurrences and pass a callback method as the second argument to the replace method and add some custom logic there:

var mystr = 'bla_3_bla_14_bla_5';

function replaceOccurrence(string, regex, n, replace) {
   var i = 0;
   return string.replace(regex, function(match) {
        i+=1;
        if(i===n) return replace;
        return match;
    });
}
console.log(
   replaceOccurrence(mystr, /\d+/g, 2, 'NUM')
)

Here, replaceOccurrence(mystr, /\d+/g, 2, 'NUM') takes mystr, searches for all digit sequences with /\d+/g and when it comes to the second occurrence, it replaces with a NUM substring.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
2

var stringWithNumbers = "bla_3_bla_14_bla_5";

var n = 1;

var changedString = stringWithNumbers.replace(/[0-9]+/g,v => n++ == 2 ? "xy" : v);

console.log(changedString);
shA.t
  • 16,580
  • 5
  • 54
  • 111
seduardo
  • 704
  • 6
  • 6