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 demo.

<body>
  <textarea id="ta"></textarea>
  
  <p>
    String to replace... <input type="text" id="txt2replace" >
  </p>
  <p>
    Replace with... <input type="text" id="replacewith" >
  </p>
  <p>
    <input type="button" value="Click to Replace" id="bt" onclick="replaceText()">
  </p>
</body>
The Script
<script>
  let replaceText = () => {
    let words = document.getElementById('ta').value;

    // Convert string to array.
    words = words.replace(/[^\w\s]/gi, '')     // remove special characters (if any).
        .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;
  }
</script>
Try it

➡️ toLowerCase() method explained - 3 examples

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).

← PreviousNext →