Why doesn't Javascript replace() work with a while loop to replace all instances?
I noticed that the replace() function only replaces the first instance of the replacement. So in order to replace all instances, I tried to use a while loop. However, this does not work. Can anyone tell me what I'm doing wrong? // define what to replace and what to replace it with var textToReplace = document.getElementById('toReplace').value; var replacementText = document.getElementById('replaceWith').value; var content = document.getElementById('content').value; // find how many times textToReplace occurs var occurrences = content.split(stringToReplace).length - 1; // set starting points var i = 0; var output = ""; // while loop while (i < occurrences) { output = content.replace(stringToReplace, replacementString); i++; } document.getElementById('content').value = output;