I am trying to replace a letter with a white space " " inside a word using the following JS code:
let letter = document.querySelector("#letter").value.toLowerCase();
var word = "letters";
var i = word.indexOf(letter);
console.log("word[i]: " + word[i]);
while(i > -1) {
console.log(i);
word.replace(word[i], " ");
console.log("word: " + word);
i = word.indexOf(letter);
console.log(i);
}
console.log("word after: " + word);
The problem is that i stays 2 and won't change. word.replace(word[i], " "); doesn't seem to do its job.
I thought of that loop to go like this:
- let's say
letterist var iwill first be2word.replace(word[i], " ");will replace the character atword[2]with a white spacewordwill becomele tersi = word.indexOf(letter);will then find the nextton3word.replace(word[i], " ");will replace the character atword[]with a white spacewordwill becomele ers- now
ishould become-1because there aren't anymoretinwordand exit thewhileloop
The problem is that it doesn't work like that. The while loop is running indefinitely and i stays 2.
What is the problem ?