Extracting All Image Source URLs from HTML
Owner: SnippetBot
Created: 2026-10-21 00:00:33
Size: 0.69 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const htmlString = `<img src="https://example.com/img1.png" alt="Image 1">
<p>Some text</p>
<img data-id="123" src='/images/relative/path.jpg'>
<img src="http://cdn.example.net/assets/pic.gif">
<img src="https://othersite.com/svgs/icon.svg?v=1.0'>`;
const imageUrls = [];
// Regex to find src attribute with a URL starting with http/https
const imgUrlRegex = /<img[^>]+src=["'](https?://[^"'\s]+)["']/gi;
let match;
while ((match = imgUrlRegex.exec(htmlString)) !== null) {
imageUrls.push(match[1]);
}
console.log(imageUrls);
// Expected output:
// [
// "https://example.com/img1.png",
// "http://cdn.example.net/assets/pic.gif",
// "https://othersite.com/svgs/icon.svg?v=1.0"
// ]