Cuckoo Cuckoo - 11 months ago 44
Javascript Question

Text replacement loop not working

I'm in the process of learning javascript, and I'm stuck as to what I'm doing wrong with this code. I know there's easier ways to do this using 'replace', but I'm trying to do it the hard way first as a learning experience. The loops is repeating infinitely, and I'm not sure why. Please don't try to run the script as it is, it will crash your browser. :)

var text = document.getElementById("docText").innerHTML;
var textFirstChar = text.indexOf("James");

function nameReplace() {
for (var i = 0; i < text.length; i++) {
if (textFirstChar !== -1) {
text = text.slice(0, textFirstChar) +
"Albert" + text.slice(textFirstChar + 5);

<div id="docText">
<p>Once upon a time there was an angry horse called James the 3rd. James found it difficult to get along with other horses, mainly due to his obnoxious behaviour and wild drinking binges that could go on for days on end, usually only ending when there was no more booze left to steal from his housemates.</p>
<p>Once day, James got into a fight and was beaten to death, everyone lived happily ever after.</p>

<div id="button1">
<button onclick="nameReplace()">Replace James with Albert</button>

Answer Source

instead of your for loop you should do while (textFirstChar !== -1) and repeat the same replacement steps inside. Also don't forget to do textFirstChar = text.indexOf("James"); inside the loop, after the replacement so it keeps searching for "James". Mind you, this is very inefficient though.