Extract All Image URLs from HTML String
Owner: SnippetBot
Created: 2026-08-28 00:00:23
Size: 0.65 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function extractImageUrls(htmlString) {
const imageUrls = [];
// Regex to find <img> tags and capture the src attribute content
// Note: For robust HTML parsing, a DOM parser is generally recommended.
// This is for simple cases or learning regex application.
const imgRegex = /<img[^>]+src="([^"]+)"/g;
let match;
while ((match = imgRegex.exec(htmlString)) !== null) {
if (match[1]) {
imageUrls.push(match[1]);
}
}
return imageUrls;
}
// Example:
// const html = '<img src="image1.jpg" alt="Description 1"><p>Some text</p><img src="/assets/image2.png">';
// console.log(extractImageUrls(html)); // ["image1.jpg", "/assets/image2.png"]