Find and Replace Text using JavaScript


In this post, we will be writing a simple JavaScript function to find and replace certain text in a HTML element.


Source Code :

 <div id="haystack">
 	By 55,000 years ago, the first modern humans, or Homo sapiens, had arrived on the Indian subcontinent from Africa, where they had earlier evolved. The earliest known modern human remains in South Asia date to about 30,000 years ago. The oldest discovered archaeological evidence of human settlements in Nepal dates to around the same time.


      	<td><input id="needle" name="needle" type="text"></td>

      	<td><input id="replacement" name="replacement" type="text"></td>

    <input type="button" value="Find" onClick="findMyText(document.getElementById('needle').value, document.getElementById('replacement').value);">
        function findMyText(needle, replacement) {
        haystackText = document.getElementById("haystack").innerHTML;

          var match = new RegExp(needle, "ig");     
          var replaced = "";
          if (replacement.length > 0) {
          	replaced = haystackText.replace(match, replacement);
        var boldText = "<div style=\"background-color: yellow; display: inline; font-weight: bold;\">" + needle + "</div>";
        replaced = haystackText.replace(match, boldText);
          document.getElementById("haystack").innerHTML = replaced;


ALSO READ  Responsive FileManager as Standalone File Manager

Comments are closed.