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. <div id="haystack">
    
  2. 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.
    
  3. </div>
    
  4. <br>
    
  5. <table>
    
  6. <tr><td>Find</td><td><input id="needle" name="needle" type="text"></td></tr>
    
  7. <tr><td>Replacment</td><td><input id="replacement" name="replacement" type="text"></td></tr>
    
  8. </table>
    
  9. <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. var haystackText = "";
  2. function findMyText(needle, replacement) {
  3.      if (haystackText.length == 0) {
  4.           haystackText = document.getElementById("haystack").innerHTML;
  5.      }
  6.      var match = new RegExp(needle, "ig");     
  7.      var replaced = "";
  8.      if (replacement.length > 0) {
  9.           replaced = haystackText.replace(match, replacement);
  10.      }
  11.      else {
  12.           var boldText = "<div style=\"background-color: yellow; display: inline; font-weight: bold;\">" + needle + "</div>";
  13.           replaced = haystackText.replace(match, boldText);
  14.      }
  15.      document.getElementById("haystack").innerHTML = replaced;
  16. }

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!





Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

9 thoughts on “How to find and replace text dynamically via JavaScript”

  1. I know this phrase has been thrown around alot on the net, but this is a friggin life saver. For two days i’ve been trying to replace element using

    newelement.innerHTML = “Something“;
    oldelement.parentNode.replaceChild(newelement, oldelement);

    and it wasn’t working, this really is a life saver, thanks.

  2. hi, very nice script. i like this replacement-stuff with javascript, because you can use it for so much different things, its interesting.

    i would like to know, is it possible to modifie this script, so that all numbers in a string are being subtracted by f.e. 1? so that 1 becomes 0, 2, becomes 1 and 255 becomes 244 (!!!) ?
    I think this might be possible somehow with some regular expressions… but im still searching for a concrete solution…

    greets, john

  3. Hi, really great tutorial thanks! Was just what I was looking for.

    I have been reading and re-reading, editing and re-editing again and again, and am a little stuck however.

    What if I wanted to find and replace two fields? How about three?
    I can’t quite seem to work out what would change to allow me to do this.

    If perhaps you could help me with this I would be very grateful.

    Cheers,
    Panda

    1. something along these lines might do the trick

      function yourFunctionName() {
      var needle= “search text here”;
      var replacementText = “XXXX”;
      var myOldString = document.getElementById(‘haystack’).innerHTML;
      var myNewString = myOldString.replace(/needle/g, replacementText);
      document.getElementById(‘haystack’).innerHTML = myNewString;

      }

  4. Sorry about that but the example code seems to have been removed.

    Here it is minus the brackets
    Param name = “OptimalDurationMultiplier value=””

    Colin

  5. Hi there

    I hope you can help me with this problem.

    I am creating a form which will output xml code for windows movie maker title files.

    I am managing to get javascript to output the code to a text-area (with the ID set as codeoutput). What I need is to find lines which contain “” as shown in example below.

    Once found I need javascript to delete all instances of these lines containing the empty quotes. Note: the strings of these lines can vary but will always contain empty quotes.

    Can this be done? If so could you please post the code to do it.

    Many thanks in advance and a Happy New Year to you.

    Regards
    Colin

  6. Hi, just wanted to say thanks for the demo on ‘how to find and replace text dynamically’. It solved a problem for me very quickly and after a couple of tweeks it serves as a nice little code generator/modifier for flv movie content.

    Thanks again!

Leave a Reply

Your email address will not be published. Required fields are marked *