I am attempting to replace a randomly selected substring within a string with another substring. Below is the code I am using:
function replaceRandomSubstring(str, substr, repl) {
var amount = str.match(substr);
var newstr = str;
if (amount.length != -1) {
var index = Math.floor(Math.random() * amount.length);
var i = 0;
do {
if (i == index) newstr = newstr.replace(substr, repl);
else newstr = newstr.replace(substr, "placeholder");
i++;
}
while (i < index);
newstr = newstr.split("placeholder").join(substr);
}
return newstr;
}
The issue I'm facing is that it only replaces the very first occurrence of the substring, not a random one as intended.