How to find and replace text dynamically via JavaScript


This is a neat little script that demonstrates two things:

1) Find – If only the Find box is filled in, then the findMyText() JavaScript function will just perform a find for the div that is given. If there is a match, the text will be highlighted and marked in bold.

2) Find and Replace – If both the Find and Replace boxes are filled in, then the findMyText() JavaScript function will do just that.

Demo
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Find
Replacment



Here is the plain HTML:

1
2
3
4
5
6
7
8
9
<div id="haystack">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</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);">

Please excuse the use of the table for the text inputs and labels. WordPress does some automatic formatting which is annoying sometimes but it is still a great application =) The only thing of importance here is on line 9 where the onClick event executes the findMyText() function and passes 2 arguments:

  • Needle – This is the text that we are trying to find in the haystack of text.
  • Replacement – This is our replacement text for any needle that we find.

Here is our JavaScript function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var haystackText = "";
function findMyText(needle, replacement) {
     if (haystackText.length == 0) {
          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;
}

Like many of the scripts that you see here, using the JavaScript DOM objects is the key to doing the find and replace dynamically for our website.

The script asks for two parameters: the needle which we are looking for in our text and the text we want to replace it with. Please note that the replacement text is totally optional. If no replacement text is given, then the behavior of the function changes a bit.

The haystackText variable is outside of the function in line 1 because we want to store the original text and always base our searches on the original text. In lines 3-5 is where we store the original text in our haystack div if it is not already set.

Line 6 creates a regular expression object where we place our needle variable along with two flags:

  • i – This flag causes the regular expression match to be case-insensitive.
  • g – This flag causes the regular expression match to be global so it matches every occurrence instead of just the first one.

Lines 8-10 checks to see if the replacement text was set. If so, we will use the replace method on our haystackText string object and feed it our match and replacement texts. The resulting string will be saved in the replaced variable.

If the replacement text was not set, the else block in lines 11-14 will be executed. We first prepare a variable of our needle that has a bit of extra styling such as a yellow background and bold text so it stands out better. Next, we just use the replace method on our haystackText string object and pass the match and replacement texts. The resulting string will be saved in the replaced variable.

Lastly, the replaced variable which contains our results is used to substitute what was originally in our haystack div.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers!