How to replace specific words in plain HTML with <A>-links using cheerio?

26 Views Asked by At

I want to replace certain words or word groups with corresponding <a>-elements that link to specific sub-pages.

Let's say, I have the following text as my DIV-body:

The decentralized exchange Balancer is currently experiencing a compromise of its interface, believed to be a DNS attack. Users should check their wallet balance.

I want to do the following replacements:

  1. "Balancer": <a href="/tags/balancer">Balancer</a>
  2. "decentralized exchange": <a href="/tags/decentralized-exchange">decentralized exchange</a>
  3. "balance": <a href="/tags/balance">balance</a>

So the final html should look like this:

The <a href="/tags/decentralized-echange">decentralized exchange<a/> <a href="/tags/balancer">Balancer</a> is currently experiencing a
compromise of its interface, believed to be a DNS attack. Users should check their wallet <a href="/tags/balance">balance</a>.

I can't use RegExp because this would replace the already replaced link to "Balancer" with another Link pointing to "Balance", which would make the first Balancer-link corrupt.

Using cheerio, I would be able to replace certain HTML elements with other elements like this:

let $ = cheerio.load(html)

$('.alt2 div:contains("Originally Posted by")')
  .replaceWith('<blockquote>Lorem ipsum dolor sit amet</blockquote>')

console.log($.html())

However, in my case, I have flat text without any selectable nodes. But after the first replacement, the flat text body will contain the first node and then a second one, which needs to be not addressed with the replacement again.

For me it is not clear, how can I replace words in text nodes, that are not really nodes like in the example above?

How can I do this with?

0

There are 0 best solutions below