title: Replacing text with HTML using Cheerio in NodeJS
body: <p>I want to replace all the occurrences of a word inside a structured HTML with a tag.</p>
  
  <p>For example, given an HTML like this</p>
  
  <pre><code>&lt;p&gt;
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, magna nec sollicitudin varius, ligula nisi finibus nulla, vel posuere libero erat eu tortor.
  &lt;/p&gt;
  &lt;p&gt;
      &lt;ul&gt;
          &lt;li&gt;Lorem&lt;/li&gt;
          &lt;li&gt;ipsum&lt;/li&gt;
          &lt;li&gt;dolor&lt;/li&gt;
          &lt;li&gt;sit&lt;/li&gt;
          &lt;li&gt;amet&lt;/li&gt;
      &lt;/ul&gt;
  &lt;/p&gt;
  &lt;p&gt;
      Lorem &lt;b&gt;ipsum&lt;/b&gt; &lt;span&gt;&lt;em&gt;dolor&lt;/em&gt;&lt;/span&gt; sit amet, consectetur adipiscing elit.
  &lt;/p&gt;
  </code></pre>
  
  <p>I would like to replace all the occurrences of the word 'ipsum' with this tag </p>
  
  <pre><code>&lt;a href="https://www.google.com/search?q=ipsum"&gt;ipsum&lt;/a&gt;
  </code></pre>
  
  <p>In this case, I tried a very simple solution that did not work:</p>
  
  <pre><code>const $ = cheerio.load(lorem_ipsum_html);
  let words = $.text().trim().split(' ');
  for (let t in words) {
      let res = words[t];
      if (words[t] == 'ipsum') res = '&lt;a href="https://www.google.com/search?q=ipsum"&gt;ipsum&lt;/a&gt;';
      $.html().replace(words[t], res);
  }
  return $.html();  
  </code></pre>
  
  <p>In this case the function returns the unchanged html, even though the replace looked like it worked.
  On top of that, I also tried to port several jQuery implementations such as: </p>
  
  <p><a href="https://stackoverflow.com/questions/6794984/replace-text-with-html-element">Replace text with HTML element</a></p>
  
  <p><a href="https://stackoverflow.com/questions/40076537/using-replace-to-replace-text-with-html">Using .replace to replace text with HTML?</a></p>
  
  <p>with no luck.</p>