2

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thanks for your reply. Unfortunately I cant use document, as its an object of window and the platform Im using is react-native. Sorry for not mentioning it in the question. Also, the space before the src is present in the html as well. @Fenton
@redberry I've provided an updated RegEx that works for this specific use-case.
my problem comes from this line 'sizes= "?"/g;', this is where the regex stops working, I think im not handling the search through sizes properly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.