0

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;

1st Nov 2019, 4:28 AM
Daryl
Daryl - avatar
5 Réponses
+ 1
The loop is unnecessary, to replace all occurrences add /g ex. str.replace(/blue/g, "red") will replace all occurrences or blue in the string with red
1st Nov 2019, 4:36 AM
JME
+ 1
Thank you, but as I'm learning Javascript, I wanted to understand why this didn't work. Also, it doesn't seem to work with my variable stringToReplace..
1st Nov 2019, 4:39 AM
Daryl
Daryl - avatar
+ 1
The loop you have replaced the first occurrence and then saves it in output over and over so it never moves on to the next occurence
1st Nov 2019, 4:57 AM
JME
+ 1
Here are examples of both methods working https://code.sololearn.com/W9jXNUQnC688/?ref=app
1st Nov 2019, 5:12 AM
JME
0
So the while loop doesn't reevaluate the replace() each time it happens? Side note, I got it to work by adding a function for replacing one instance, then run that function in a while loop. function replaceOne() { // 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; // see if the string exists if (content.search(stringToReplace) === -1) { alert("The string to replace could not be found."); } var output = content.replace(stringToReplace, replacementString); // assign output to the document document.getElementById('stringContainer').value = output; } // 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) { // define all the required variables again because of scope replaceOne(); i++; }
1st Nov 2019, 5:13 AM
Daryl
Daryl - avatar