JavaScript - Replace all instances of a particular string in a textarea

← PrevNext →

Let us assume, I have a textarea in my web page. I copy pasted a paragraph in the textarea and then realized that a particular text with multiple instances must be replaced with another text, before I submit the para. I could have done this using Ms-Word or any text editor tool. However, I can do this instantly (on the web page itself) with the click of a button using JavaScript.
The Markup

I have a textarea, 2 textboxes and a button. The two textboxes, one I'll enter the text or the string that I want to replace and the second I'll enter the text (or the string) to replace with. See this example in action.

  <textarea id="ta"></textarea>
    String to replace... <input type="text" id="txt2replace" >
    Replace with... <input type="text" id="replacewith" >
    <input type="button" value="Click to Replace" id="bt" onclick="replaceText()">
The Script
  let replaceText = () => {
    let words = document.getElementById('ta').value;
    words = words.replace(/[^\w\s]/gi, '').replace('\n\n', ' ').split(' ');

    let txt2replace = document.getElementById('txt2replace').value;
    let replace_with = document.getElementById('replacewith').value;
    let map = '';
    words.forEach(function (item) {
      if (item.toLowerCase() == txt2replace) {
        item = replace_with;
      map = map + ' ' + item;

    document.getElementById('ta').value = map;
Try it

It first extracts the words from the textarea and creates an array. It now becomes easy to work with each word one by one.

It then loops through each item in the array, checks for a possible match and replaces the text (word or string) with a new string (or text).

That's it. 🙂

← PreviousNext →