Find and replace nth occurrence of [bracketed] expression in string

Here is another possible solution. You can pass the string.replace function a function to determine what the replacement value should be. The function will be passed three arguments. The first argument is the matching text, the second argument is the position within the original string, and the third argument is the original string.

The following example will replace the second “L” in “HELLO, WORLD” with “M”.

var s = "HELLO, WORLD!";
var nth = 0;
s = s.replace(/L/g, function (match, i, original) {
    nth++;
    return (nth === 2) ? "M" : match;
});
alert(s); // "HELMO, WORLD!";

See MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

Leave a Comment