How to display only image from HTML

Viewed 89

Hello,

I have a React app and I'm fetching the Blogger API using axios. In the response, there is a content property. It contains HTML, but in string like this:

   {
       "content": "<div> some content </div>"
   }

So I'm using react-html-parser package to convert it to JSX.

The problem is, I want to take the first <img/> from this content JSX and display only it - hide other elements.


I tried set display: none for * and display: block for img, but then nothing was visible - including image.



Thanks in advance

3 Answers

You can first extract the image tag as string and then display it via react-html-parser

Try this

let imageTagStr = content.match(/<img\s+[^>]*src="([^"]*)"[^>]*>/i);

You can do this by firstly editing the string to isolate the tag:

const firstSplit = content.split('<img')[1].split('/>')[0].concat('/>');
const finalsplit = '<img'.concat(firstSplit);

What is this doing?

  1. Split the string where the <img tag starts and grab the second part of that split
  2. Split it again where it ends and grab the first part of that string
  3. Add to the string /> because that was split by step two
  4. Add <img to the front of the firstSplit because that was split in step one

OR

Using regex and .match you can do something like this:

content.match(/<img\s+[^>]*src="([^"]*)"[^>]*>/i);

This is not a React problem. Why not try to turn your html string into Dom elements using :

let doc = new DOMParser().parseFromString(YOUR_STRING, "text/xml");

And then parse it using just javascript.

Related