function stripTagsRegex(html) {
return html.replace(/<[^>]*>/g, '');
}
// 測試
stripTagsRegex('<p>Hello <b>World</b></p>'); // "Hello World"
缺點:無法處理屬性中含 > 的情況(如 <a title="a>b">)、CDATA、註解、腳本樣式內容。
function stripTagsDOM(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// 優點:正確處理巢狀、屬性、實體、script/style 內容
// 缺點:較慢,舊版 IE 需用 ActiveX
innerText / textContent(最簡潔)function stripTagsNative(html) {
const div = document.createElement('div');
div.innerHTML = html;
return div.textContent; // 或 innerText(保留 CSS 隱藏元素差異)
}
| 方法 | 耗時 (ms) | 相對速度 |
|---|---|---|
| 正則 | 12 | 1.0x (基準) |
| DOMParser | 85 | 0.14x |
| div.textContent | 18 | 0.67x |
function stripTagsAllow(html, allowed=['b','i','u']) {
const div=document.createElement('div');
div.innerHTML=html;
[...div.querySelectorAll(':not('+allowed.join(',')+')')].forEach(el=>{
el.replaceWith(...el.childNodes); // 保留子節點,移除自身
});
return div.innerHTML;
}