Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex extract img src javascript

I am trying to extract the img and src from a long html string.

I know there are a lot of questions about how to do this, but I have tried and gotten the wrong result. My question is just about contradicting results though.

I am using:

var url = "<img height=\"100\" src=\"data:image/png;base64,testurlhere\" width=\"200\"></img>";
var regexp = /<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>/g;
var src = url.match(regexp);

But this results in src not being extracted properly. I keep getting src =<img height="100" src="data:image/png;base64,testurlhere" width="200"></img> instead of data:image/png;base64,testurlhere

However, when I try this on the regex tester at regex101, it extracts the src correctly. What am I doing wrong? Is match() the wrong function to use>

like image 280
llams48 Avatar asked Jul 09 '26 12:07

llams48


1 Answers

If you need to get the whole img tags for some reason:

const imgTags = html.match(/<img [^>]*src="[^"]*"[^>]*>/gm);

then you can extract the source link for every img tag in array like this:

const sources = html.match(/<img [^>]*src="[^"]*"[^>]*>/gm)
                          .map(x => x.replace(/.*src="([^"]*)".*/, '$1'));
like image 100
Vi0nik Avatar answered Jul 12 '26 02:07

Vi0nik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!