Replace nth occurence of number in string with javascript [duplicate]

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

Answers:

Answer

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.

Answer

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);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.