0

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 is t
  • var i will first be 2
  • word.replace(word[i], " "); will replace the character at word[2] with a white space
  • word will become le ters
  • i = word.indexOf(letter); will then find the next t on 3
  • word.replace(word[i], " "); will replace the character at word[] with a white space
  • word will become le ers
  • now i should become -1 because there aren't anymore t in word and exit the while 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 ?

  • 3
    strings are immutable. `replace` returns a new string which you need to reassign. `word = word.replace(...)`. You can also use regex to do this without while: `word.replace(new RegExp(letter ,"g"), " ")` – adiga Jan 12 '20 at 10:57
  • Could you present your question in terms of "given input X, then the desired output is Y, but problem Z occurs in this code"? – dryleaf Jan 12 '20 at 11:00
  • @adiga `word = word.replace(word[pos], "");` works nicely. The regex solution sounds even better. but needs a little bit more research on my end. Thanks ! – GeorgicaFaraFrica Jan 12 '20 at 11:07
  • @adiga `word = word.replace(new RegExp(letter ,"g"), "");` works wonders and is much cleaner. – GeorgicaFaraFrica Jan 12 '20 at 11:14

1 Answers1

1

You can use the regex /t/g

Check snippet:

//let replace = document.querySelector("#letter").value.toLowerCase();
var replace = "t";
var re = new RegExp(replace,"g");

var original_text="letters";
var extracted_text = original_text.replace(re, ' ');
console.log(extracted_text);
Basil
  • 1,613
  • 12
  • 25
  • But how can I use regex with variables ? You've put `t` inside `/t/g`. I want to put `letter` which is `let letter = document.querySelector("#letter").value.toLowerCase();` – GeorgicaFaraFrica Jan 12 '20 at 11:06
  • updated my code, are you able to upvote and mark as correct after closing your question? – Basil Jan 12 '20 at 11:09
  • `word = word.replace(new RegExp(letter ,"g"), "");` works wonders and is much cleaner than my `while` loop. – GeorgicaFaraFrica Jan 12 '20 at 11:15