RiesvGeffen
RiesvGeffen

Reputation: 1589

Trying to get <img> tags from text with subString and indexOf

So I got a variable called text and in there are HTML entities. My code is working fine, because I'm getting the whole <img ...> tag. But this is the problem sometimes there are more then 1 <img> tag. Now my question is how do I get all of those <img> tags, I was thinking about something like adding /g at the end of indexof, but that wasn't a success.

This is what I have so far:

var images = text.substring((text.indexOf("<img")), ((text.indexOf("/>")) + 2));

Upvotes: 0

Views: 696

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use match() with regex <img[^>]*\/?>

var text = `
<img src="#" />
<img src="sss.jpg" />
`;

var images = text.match(/<img[^>]*\/?>/g);

console.log(images);

Regex explanation here

Regular expression visualization

Upvotes: 2

Rando Hinn
Rando Hinn

Reputation: 1322

What you could do is along these lines

 var tags = [];
 var re = /<img?([^/>]+)?/>/g, match;
 while(match = re.exec(text)) {
     tags.push(match[0]);
 }

tags would then contain all the found image tags.

Upvotes: 0

void
void

Reputation: 36703

Make text string a jQuery object

$(text)

Find all the img using

$(text).find('img').addBack('img')

Upvotes: 0

Related Questions