cheerio icon indicating copy to clipboard operation
cheerio copied to clipboard

How to "replaceWith" on plain text, which is not a DOM Elements?

Open opendeluxe opened this issue 1 year ago • 5 comments

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?

opendeluxe avatar Sep 30 '23 07:09 opendeluxe

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

SagarKapoorin avatar Oct 01 '23 09:10 SagarKapoorin

Can you tell me in which file this issue occurs.

SagarKapoorin avatar Oct 01 '23 09:10 SagarKapoorin

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.

opendeluxe avatar Oct 01 '23 10:10 opendeluxe

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

SagarKapoorin avatar Oct 01 '23 11:10 SagarKapoorin

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 ?

luv2027 avatar Oct 05 '23 05:10 luv2027

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')

fb55 avatar Aug 08 '24 08:08 fb55