title: find-and-replace iteration with javascript
body: <p>I am making a text editor for my website, and I need a find-and-replace function that finds each time the text occurs, highlights it, and, if the user chooses to, replaces it. Then it moves onto the next occurrence, and does the same thing.
  I saw this code:</p>
  
  <pre><code>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 &gt; 0) {
            replaced = haystackText.replace(match, replacement);
       }
       else {
            var boldText = "&lt;div style=\"background-color: yellow; display: inline; font-weight: bold;\"&gt;" + needle + "&lt;/div&gt;";
            replaced = haystackText.replace(match, boldText);
       }
       document.getElementById("haystack").innerHTML = replaced;
  }
  </code></pre>
  
  <p>but it only works with a div that has text it, and not a textarea, like I have, and also, it finds and/or replaces all of the occurrences at once, instead of iterating through them one by one.</p>
  
  <p>How can I make this work?</p>