I am trying to replace random substring with another within a string. This is my code
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;
}
What's happening is that it replaces the very first substring not random one
substronly, not a random amount of the occurrences?