holographix
holographix

Reputation: 2557

Replacing text with HTML using Cheerio in NodeJS

I want to replace all the occurrences of a word inside a structured HTML with a tag.

For example, given an HTML like this

<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, magna nec sollicitudin varius, ligula nisi finibus nulla, vel posuere libero erat eu tortor.
</p>
<p>
    <ul>
        <li>Lorem</li>
        <li>ipsum</li>
        <li>dolor</li>
        <li>sit</li>
        <li>amet</li>
    </ul>
</p>
<p>
    Lorem <b>ipsum</b> <span><em>dolor</em></span> sit amet, consectetur adipiscing elit.
</p>

I would like to replace all the occurrences of the word 'ipsum' with this tag

<a href="https://www.google.com/search?q=ipsum">ipsum</a>

In this case, I tried a very simple solution that did not work:

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 = '<a href="https://www.google.com/search?q=ipsum">ipsum</a>';
    $.html().replace(words[t], res);
}
return $.html();  

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:

Replace text with HTML element

Using .replace to replace text with HTML?

with no luck.

Upvotes: 1

Views: 4546

Answers (3)

Marinos An
Marinos An

Reputation: 10868

Clean solution:

This is the code that does it by iterating all dom text nodes:

const $ = require('cheerio').load(inputHtml);
const getTextNodes=(elem)=>elem.type==='text'?[]:
        elem.contents().toArray()
        .filter(el=>el!==undefined)//I don't know why some elements are undefined
        .reduce((acc, el)=>
            acc.concat(...el.type==='text'?[el]:getTextNodes($(el))), [] )
    
    
const replaceRegex = /ipsum/g;
const replacementTag =  `<a href="https://www.google.com/search?q=ipsum">ipsum</a>`;

getTextNodes($(`html`))
    .filter(node=>$.html(node).match(replaceRegex))
    .map(node=>$(node).replaceWith($.html(node).replace(replaceRegex,replacementTag))  );

console.log($.html());

Output:

<html><head></head><body><p>
    Lorem <a href="https://www.google.com/search?q=ipsum">ipsum</a> dolor sit amet, consectetur adipiscing elit. Fusce porttitor, magna nec sollicitudin varius, ligula nisi finibus nulla, vel posuere libero erat eu tortor.
</p>
<p>
    </p><ul>
        <li>Lorem</li>
        <li><a href="https://www.google.com/search?q=ipsum">ipsum</a></li>
        <li>dolor</li>
        <li>sit</li>
        <li>amet</li>
    </ul>
<p></p>
<p>
    Lorem <b><a href="https://www.google.com/search?q=ipsum">ipsum</a></b> <span><em>dolor</em></span> sit amet, consectetur adipiscing elit.
</p></body></html>

Original answer here

Upvotes: 0

Saeed
Saeed

Reputation: 5488

1- Load body with cheerio

var $ = cheerio.load(body);

2- With this recursive function you can replace your target in all elements and their children

function replacer($, text) {
    if ($(text).children().length) {
        $(text).children().each(function (itm) {
            return replacer($, $(this));
        });
    }
    else {
        var value = $(text).text();
        value = value.replace(/ipsum/g, '<a href="https://www.google.com/search?q=ipsum">ipsum</a>');
        return $(text).text(value);
    }
}

3- Turn cheerio dom nodes back to html with this

return $.html(bb);

4- Replace all &quot;, &lt; and &gt; with right symbols.

f(b).replace(/&lt;/g,'<').replace(/&gt;/g, '>').replace(/&quot;/g, '"')

I hope this helps you. Just modify where you want of code

var b = `<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce porttitor, magna nec sollicitudin varius, ligula nisi finibus nulla, vel posuere libero erat eu tortor.
</p>
<p>
<ul>
    <li>Lorem</li>
    <li>ipsum</li>
    <li>dolor</li>
    <li>sit</li>
    <li>amet</li>
</ul>
</p>
<p>
Lorem <b>ipsum</b> <span><em>dolor</em></span> sit amet, consectetur adipiscing elit.
</p>`;

var cheerio = require('cheerio');

function replacer($, text) {
  if ($(text).children().length) {
    $(text).children().each(function(itm) {
      return replacer($, $(this));
    });
  } else {
    var value = $(text).text();
    value = value.replace(/ipsum/g, '<a href="https://www.google.com/search?q=ipsum">ipsum</a>');
    return $(text).text(value);
  }
}

function f(body) {
  var $ = cheerio.load(body);
  var bb = $("p").each(function(itm) {
    return replacer($, $(this));
  });
  return $.html(bb);
}

console.log(f(b).replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"'))

Output:

<p>
  Lorem <a href="https://www.google.com/search?q=ipsum">ipsum</a> dolor sit amet, consectetur adipiscing elit. Fusce porttitor, magna nec sollicitudin varius, ligula nisi finibus nulla, vel posuere libero erat eu tortor.
</p>
<p>
  <ul>
    <li>Lorem</li>
    <li><a href="https://www.google.com/search?q=ipsum">ipsum</a></li>
    <li>dolor</li>
    <li>sit</li>
    <li>amet</li>
  </ul>
</p>
<p>
  Lorem <b><a href="https://www.google.com/search?q=ipsum">ipsum</a></b> <span><em>dolor</em></span> sit amet, consectetur adipiscing elit.

Upvotes: 4

holographix
holographix

Reputation: 2557

I ended up with this (not so clean) solution. It's not the best thing in the world but it works. There's still room for improvement here.

let $ = cheerio.load(lorem_ipsum_html);
let words = $.text().trim().split(' ');
for (let t in words) {
    let res =  words[t];
    if(words[t] == 'ipsum') res = '<a href="https://www.google.com/search?q=ipsum">ipsum</a>';
    let $ = cheerio.load($.html().replace(words[t], res));
}
return $.html();

In this case the HTML structure remain intact, and the anchor tags are just injected in the right place.

<p>
    Lorem <a href="https://www.google.com/search?q=ipsum">ipsum</a> dolor sit amet, consectetur adipiscing elit. Fusce porttitor, magna nec sollicitudin varius, ligula nisi finibus nulla, vel posuere libero erat eu tortor.
</p>
<p>
    <ul>
        <li>Lorem</li>
        <li><a href="https://www.google.com/search?q=ipsum">ipsum</a></li>
        <li>dolor</li>
        <li>sit</li>
        <li>amet</li>
    </ul>
</p>
<p>
    Lorem <b><a href="https://www.google.com/search?q=ipsum">ipsum</a></b> <span><em>dolor</em></span> sit amet, consectetur adipiscing elit.
</p>

Upvotes: 0

Related Questions