Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
Javascript find and replace function using while loop

I have this simple function to find and replace text in my textarea message. User will be able to type into the textarea and also be able to find and replace words from the text area they just entered. Currently I'm trying to use a while loop to replace multiple same words found in the textarea that the user keyed in. But every time I run it it seems to freeze the entire html page any idea why this is happening?

find and replace are textbox for user to key in the word they want to find and replace the user is able to key in multiple words to replace as well.

function findText() {
  let find = document.getElementById('find').value;
  let replace = document.getElementById('replace').value;
  let message = document.getElementById('message').value;
  var lmao = message.indexOf(find);

  while (message.indexOf(find) != -1) {
    document.getElementById("message").value = message.replace(find, replace);
  }
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Replace while loop with a replaceAll.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

function findText() {

  let find = document.getElementById('find').value;
  let replace = document.getElementById('replace').value;
  let message = document.getElementById('message').value;
  var lmao = message.indexOf(find);

  document.getElementById("message").value = message.replaceAll(find, replace);

}
<div>Find <input id="find" value="find" /></div>
<div>Replace <input id="replace" value="replace" /></div>
<div>
  <textarea id="message" style="height: 100px">you can find and replace every words just by .replaceAll, example: find 1 find 2 find 3</textarea>
</div>
<div>
  <button onclick="findText()">Submit</button>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Just a addition in other answer you can use g for global search and to replace where you find that word . Read more about regex and //g here

Also you can let the search case-insensitivity using i along with g like this :
message.replace(/find/g, replace)
This way it will also replace Find finD FIND

And instead of using while you can use if loop

function findText() {

  let find = document.getElementById('find').value;
  let replace = document.getElementById('replace').value;
  let message = document.getElementById('message').value;
  var lmao = message.indexOf(find);

  if(message.indexOf(find) != -1) {

    document.getElementById("message").value = message.replace(/find/g, replace);

  }

}
<div>Find <input id="find" value="find" /></div>
<div>Replace <input id="replace" value="replace" /></div>
<div>
  <textarea id="message" style="height: 100px">you can find and replace every words just by .replaceAll, example: find 1 find 2 find 3</textarea>
</div>
<div>
  <button onclick="findText()">Submit</button>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

The issue is with your while condition. When all input fields are empty your while condition is true. So inside the while condition the input value keeps on updating to empty string again, which makes loop an infinite loop. Thats why your ui is breaking.

Issue Scenario

console.log(("").indexOf("") !== -1);

To fix this, you have to make sure that your find and replace values are not same. Or else, it will be an infinite loop again.

Fixed Solution

function findText() {
  let find = document.getElementById('find').value;
  let replace = document.getElementById('replace').value;
  let message = document.getElementById('message');
  while (find !== replace && message.value.indexOf(find) != -1) {
    message.value = message.value.replace(find, replace);
  }
}
<input type="text" id="find">
<input type="text" id="replace">
<textarea name="" id="message" cols="30" rows="10"></textarea>
<button onclick="findText()">Check</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda