JAVASCRIPT
Extract All Image URLs from HTML Content
Discover how to extract all image source URLs (src attributes) from an HTML string using a regular expression in JavaScript, perfect for content parsing tasks.
const imageUrlRegex = /<img[^>]+src="([^">]+)"/g;
function extractImageUrls(htmlContent) {
const urls = [];
let match;
while ((match = imageUrlRegex.exec(htmlContent)) !== null) {
urls.push(match[1]);
}
return urls;
}
// Example usage:
// const html = '<p>Some text</p><img src="image1.jpg" alt="Img 1"><img src="https://example.com/image2.png">';
// console.log(extractImageUrls(html)); // ["image1.jpg", "https://example.com/image2.png"]
How it works: This snippet uses a regular expression to find all `<img>` tags within an HTML string and capture the content of their `src` attributes. The `g` flag ensures that all matches are found, and the `while` loop with `exec()` method iterates through them, pushing each extracted URL into an array. This is highly useful for parsing dynamic content or extracting assets.