前端常見需求:將含 HTML 的字串轉為純文字、或清空容器內容。本文比較 innerHTML、textContent、Regex 三種做法的差異、效能與適用場景。
// 方法 1:innerHTML = ''(最常用,觸發重繪)
document.getElementById('container').innerHTML = '';
// 方法 2:removeChild 迴圈(大量子節點時較快)
const el = document.getElementById('container');
while (el.firstChild) el.removeChild(el.firstChild);
// 方法 3:textContent = ''(不解析 HTML,極快)
el.textContent = '';
建議:單純清空用 textContent = '' 效能最好;需觸發框架綁定更新時用 innerHTML = ''。
function htmlToText(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// 測試
htmlToText('<div>Hello <b>World</b> </div>'); // "Hello World "
document.createElement('div').innerHTML = html 替代function htmlToTextFast(html) {
const tmp = document.createElement('div');
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || '';
}
注意:舊版 IE 需用 innerText;若 HTML 含 <script> 可能觸發執行(現代瀏覽器已阻擋)。
function stripTagsRegex(html) {
return html
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/<[^>]+>/g, '')
.replace(/ /g, ' ')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\s+/g, ' ')
.trim();
}
缺點:無法處理跨行屬性、CDATA、條件式註解等邊緣案例。
| 方法 | 約耗時 | 適用場景 |
|---|---|---|
| DOMParser | ~120ms | 通用、需解碼實體、含 script/style |
| div.innerHTML + textContent | ~80ms | 輕量、瀏覽器環境、信任來源 |
| Regex | ~40ms | Node.js、Worker、極大字串、不需實體解碼 |
textContent 賦值,避免 XSSwhite-space: pre-wrap 或轉 <br>// 瀏覽器:最簡單
const text = new DOMParser().parseFromString(html, 'text/html').body.textContent;
// Node.js (無 DOM):引入 jsdom 或用 regex
const { JSDOM } = require('jsdom');
const text = new JSDOM(html).window.document.body.textContent;
根據執行環境、資料來源可信度、效能需求選擇適當方案。現代瀏覽器首推 DOMParser,兼顧正確性與安全性;Node.js 推薦 jsdom 或成熟函式庫 striptags、html-to-text。