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.
</div>

    <br>

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

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

    <input type="button" value="Find" onClick="findMyText(document.getElementById('needle').value, document.getElementById('replacement').value);">
    
    <script>
        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);
          }
      else{
        var boldText = "<div style=\"background-color: yellow; display: inline; font-weight: bold;\">" + needle + "</div>";
        replaced = haystackText.replace(match, boldText);
          }
          document.getElementById("haystack").innerHTML = replaced;
      }
    </script>

 



Recommended For You

About the Author: Admin