Change the position of a word in the text (Javascript)

Asked

Viewed 202 times

1

I would like to change the position of a word inside a text using javascript.

<form>
  <p> Este é o paragrafo, esta é <strong>palavra</strong> a ser movida </p>
  <span>Troque aqui a posicao da <strong>palavra</strong>no texto : </span>
  <input type="range">
</form>

2 answers

1


Here is a more elaborate version making use of the input[type=range]

document.getElementById('posicao').addEventListener("input", function() {
  var posicao = this.value; //guarda a posicao do input
  var palavra = document.querySelector('p strong').innerText; // busca a palavra que esta no <strong>
  var texto = document.querySelector('p').innerText.replace(palavra, ''); //remove a palavra do texto
  var pos = Math.floor((posicao*texto.length)/100); //define a nova posicao da palavra, quase como a regras dos 3 simples
  document.getElementById('novo_texto').innerHTML=texto.slice(0,pos)+' <strong>'+palavra+'</strong> '+texto.slice(pos); // insere a palavra no texto
});
<p> Este é o paragrafo, esta é <strong>palavra</strong> a ser movida </p>
<input type="range" id="posicao">
<p id="novo_texto"></p>

Good Luck!

  • 1

    Thanks dad !!!

0

Save text in a variable

var txt = "Este é o paragrafo, esta é **palavra** a ser movida"

Keep the word in a variable

var word = "palavra"

After selecting the positionvar pos Makes:

var novotxt=[t.slice(0,pos), word, t.slice(pos)].join(" ")

Here the text is divided into two parts, and the desired word is placed in the chosen position. These "pieces" of text are in the array, and then made join() to compose the novotxt

Browser other questions tagged

You are not signed in. Login or sign up in order to post.