cheerio
cheerio copied to clipboard
How to "replaceWith" on plain text, which is not a DOM Elements?
I have the following DIV that needs some replaces:
const html = `Lorem Ipsum dolores`;
const $ = cheerio.load(html, null, false);
This loads the string without wrapping the text into <html><body>
, which must be avoided in my case.
I want to do a replacement on "Ipsum" to replace it with a DOM element, like an <a>
-Element.
After that, I want to replace other words as well with related DOM-elements, but never ever touch already replaced words again.
Which filter gives me this feature to work with replaceWith
?
hi there, I'm relatively new to this project, so please correct me if I'm mistaken. So the issue you facing is:- You want to replace specific words in an HTML string with DOM elements (e.g., replacing "Ipsum" with an element), but you also want to ensure that once a word has been replaced, it won't be replaced again
Can you tell me in which file this issue occurs.
Yes, lets say I get an article from a CMS, it can contain HTML like a
-links or divs
or span
-elements or nothing at all.
I want to replace specific words or word groups to with specific <a>
-elements to deep link into other articles. No matter, if this word is part of a span
-element or a div
or a p
-element or plain text which is not at all encapsulated within an HTML tag. But i this word is part of an a
-element, it should not be replaced again as it is already a link.
Ok i got it ,I am Looking for existing file where this existing code is written as i am unable to find code where i have to make changes
I have the following DIV that needs some replaces:
const html = `Lorem Ipsum dolores`; const $ = cheerio.load(html, null, false);
This loads the string without wrapping the text into
<html><body>
, which must be avoided in my case.I want to do a replacement on "Ipsum" to replace it with a DOM element, like an
<a>
-Element. After that, I want to replace other words as well with related DOM-elements, but never ever touch already replaced words again.Which filter gives me this feature to work with
replaceWith
?
Can you tell me in which file the changes needs to be made ?
Your best bet is likely to find the text
node in the tree, then update its data
property directly:
const text = $('body').get(0).childNodes[0]
text.data = text.data.replace('Ipsum', 'Possum')