Regex expression on html image string

Viewed 64

I'm struggling with completing a regex expression, and it would be greatly appreciated if someone could help.

I'm trying to get the source of the image from this HTML div tag

<div class="preview item"><img alt=""
    sizes="(max-width: 440px) 320px"
    src= "https://m.testlink.com/test/zx320y230c_4130512.jpg"
    srcset= "https://m.testlink.com/test/zx320y230c_4130512.jpg 320w, https://m.testlink.com/test/zx640y460c_4130512.jpg 640w"></div>

Here is what I have so far:

const imgRegX = /<div class="?preview item"?[^>]*>\s*<img alt="?" sizes= "?"/g;

For some reason when I add the sizes it breaks.

I also assume this is how the src regex would look like, but so far I can't figure out the sizes.

src="?([^"\s]+)/
1 Answers

You can use elements to get this information from the document without using a RegEx. For example, the below extracts the src attribute for all images that are children of the "preview" div.

const previews = document.getElementsByClassName('preview');

for (let item of previews) {
    var images = item.getElementsByTagName('img');
    
    for (let img of images) {
        console.log('Source:', img.src);
    }
}
<div class="preview item"><img alt=""
    sizes="(max-width: 440px) 320px"
    src= "https://m.testlink.com/test/zx320y230c_4130512.jpg"
    srcset= "https://m.testlink.com/test/zx320y230c_4130512.jpg 320w, https://m.testlink.com/test/zx640y460c_4130512.jpg 640w"></div>

RegEx Problem

Your RegEx problem is caused by an unexpected space here: src= " There is a space before the quote, which means it no longer matches your expression. The below screenshot is taken from RegEx101.

You could cater for the whitespace after the = sign in your RegEx:

src=\s"?([^"\s]+)

RegEx Test

Related