JAVASCRIPT
Extract Image `src` Attributes from HTML
Efficiently parse HTML strings to extract all `src` attribute values from `<img>` tags, useful for image processing or content analysis.
function extractImageSrc(htmlString) {
const regex = /<img[^>]+src="([^"]+)"/g;
const matches = [...htmlString.matchAll(regex)];
return matches.map(match => match[1]);
}
// Example usage:
// const html = '<img src="image1.jpg" alt="Description 1"><p>Some text</p><img src="/assets/image2.png" data-id="123">';
// console.log(extractImageSrc(html));
How it works: This JavaScript function parses an HTML string to find and extract the `src` attribute values from all `<img>` tags. The regular expression `/<img[^>]+src="([^"]+)"/g` looks for the `<img` tag, followed by any characters that are not a closing angle bracket (`>`) to ensure it stays within the tag, then specifically matches `src="` and captures any characters (`[^"']+`) until the closing quote. The global flag `g` ensures all image sources are extracted, and `matchAll` is used to get all capture groups.