function stripTags(html) {
// 建立獨立文檔,不執行腳本、不載入外部資源
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// 進階:保留換行、移除 script/style 內容
function stripTagsAdvanced(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
// 移除 script、style、noscript
doc.querySelectorAll('script, style, noscript').forEach(el => el.remove());
// 將區塊元素轉為換行
doc.querySelectorAll('div, p, br, li, h1, h2, h3, h4, h5, h6, blockquote').forEach(el => {
el.appendChild(document.createTextNode('\n'));
});
return doc.body.textContent.replace(/\n{3,}/g, '\n\n').trim();
}
優點:瀏覽器原生解析器處理邊界情況 (屬性值含 >、CDATA、註釋、實體編碼);不執行 JS;支援 SVG/MathML。
缺點:Node.js 需額外套件 (jsdom、linkedom);大量字串效能較差。
// 基礎版
const stripTags = html => html.replace(/<[^>]*>/g, '');
// 進階版:處理跨行、註釋、CDATA
const stripTagsAdvanced = html => html
.replace(//g, '') // 移除註釋
.replace(//g, '') // 移除 CDATA
.replace(/