從 HTML 字串中提取所有 <img> 標籤及其 src 屬性是常見需求(如編輯器、爬蟲、內容分析)。本文提供健全的正則表達式方案並說明注意事項。
<img> 標籤。src 屬性值。// 匹配 img 標籤(支援自閉合、屬性順序不固定)
const imgReg = /<img\s+[^>]*?\/?>/gi;
// 提取 src 屬性(支援單雙引號、無引號)
const srcReg = /src\s*=\s*['"]?([^'"\s>]+)['"]?/i;
<script>
const html = `<img src="https://a.com/1.jpg" alt="A">
<img src='https://b.com/2.png' />
<img src=https://c.com/3.gif width=100>`;
// 1. 取得所有 img 標籤
const imgTags = html.match(imgReg) || [];
// 2. 逐個提取 src
const srcList = imgTags.map(tag => {
const match = tag.match(srcReg);
return match ? match[1] : null;
}).filter(Boolean);
console.log(srcList);
// ["https://a.com/1.jpg", "https://b.com/2.png", "https://c.com/3.gif"]
</script>
function extractImages(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
return Array.from(doc.querySelectorAll('img')).map(img => img.src);
}
DOMParser 或 cheerio (Node.js) 等 HTML 解析器。src 可能為相對路徑,需搭配 new URL(src, baseUrl) 轉絕對路徑。正則方案適合簡單、可控的 HTML 片段;複雜或不可信輸入請改用標準 HTML 解析器,確保正確性與安全性。