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