0

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>
<div id="button1">
<button onclick="nameReplace()">Replace James with Albert</button>
</div>

asked Sep 18, 2016 at 12:02

1 Answer 1

2

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.

answered Sep 18, 2016 at 12:08
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I knew I was missing something obvious. I also didn't put a statement in to actually replace the text, which I've now done. Many thanks! :)
No problem, glad I could help :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.