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
letter
ist
var i
will first be2
word.replace(word[i], " ");
will replace the character atword[2]
with a white spaceword
will becomele ters
i = word.indexOf(letter);
will then find the nextt
on3
word.replace(word[i], " ");
will replace the character atword[]
with a white spaceword
will becomele ers
- now
i
should become-1
because there aren't anymoret
inword
and exit thewhile
loop
The problem is that it doesn't work like that. The while
loop is running indefinitely and i
stays 2.
What is the problem ?