JAVASCRIPT

Extract All Image `src` Attributes from an HTML String

Efficiently find and extract all image `src` attribute values from a given HTML string using JavaScript regular expressions and `matchAll`.

const htmlContent = '<img src="image1.jpg" alt="Description 1"><p>Some text</p><img src="/path/to/image2.png" data-id="123"><img src="https://cdn.example.com/image3.gif">';
const imgSrcRegex = /<img[^>]+src="([^"]+)"/gi;
const srcMatches = Array.from(htmlContent.matchAll(imgRegex), match => match[1]);

console.log(srcMatches);
How it works: This JavaScript snippet uses `matchAll` with a regular expression to extract all `src` attribute values from `<img>` tags within an HTML string. The regex `/<img[^>]+src="([^"]+)"/gi` specifically looks for `<img>` tags, then for the `src` attribute, and captures its value (anything inside the double quotes) into a group. `Array.from(matchAll, ...)` then converts the iterator of matches into an array containing only the captured `src` URLs, which is very useful for image processing or CDN integration.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs