lepsztyk lepsztyk - 22 days ago 7
jQuery Question

How to make a javascript that will change words on the site?

I have something like this

<html>

<body>
<h> Hello everybody, what's up? </h>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Cras ex arcu,consequat sit amet volutpat vitae, finibus vel massa.
Sed eleifend quis justo eu auctor.
</p>
Swap from:<br>
<input type="text" name="from"><br>
Swap to:<br>
<input type="text" name="to"><br><br>
<input type="submit" value="DO IT!">
</body>

</html>


I would like to add a script that would change the word given by me in the 'Swap from' text box into the another word given by me in the 'Swap to' text box and appear in the Lorem ipsum text.

I know there should be something like:

<button onclick="replaceText()">Click me!</button>


and some javascript to get the values from 'Swap from' and 'Swap to' but I cannot figure it out.

Answer

No jQuery, pure JavaScript. Enjoy.

function swap() {
  var first = document.getElementById('from').value;
  var text = document.getElementById('text');
  var second = document.getElementById('to').value;

  text.innerHTML = text.innerHTML.replace(new RegExp(first, 'g'), second);
}
button {
  height: 30px;
  width: 100px;
}
<h>Hello everybody, what's up?</h>
  <p id='text'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ex arcu,consequat sit amet volutpat vitae, finibus vel massa. Sed eleifend quis justo eu auctor.
  </p>
  Swap from:
  <br>
  <input id='from' type="text" name="from">
  <br>Swap to:
  <br>
  <input id='to' type="text" name="to">
  <br>
  <br>
  <button onclick="swap()" type="submit" value="DO IT!">Do it!</button>