從 CKEditor 等富文本編輯器取得內容時,HTML 特殊字元已被轉義為實體(如 <, ")。傳遞給後端或儲存前需正確解碼,避免內容截斷或顯示異常。
// 缺點:不完整、效能差、易遺漏實體
content = content.replace(/"/g, '"');
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
content = content.replace(/'/g, "'");
content = content.replace(/&rduot;/g, '“'); // 拼寫錯誤:應為 ”
function decodeHtmlEntities(str) {
const textarea = document.createElement('textarea');
textarea.innerHTML = str;
return textarea.value;
}
// 使用範例
const decoded = decodeHtmlEntities('<div>Hello</div>');
// 結果:'Hello'
原理:瀏覽器解析 innerHTML 時會自動解碼 HTML 實體,textarea.value 取得純文字。
function decodeHtmlEntities(str) {
const parser = new DOMParser();
const doc = parser.parseFromString(str, 'text/html');
return doc.documentElement.textContent;
}
npm install he_.unescape(str)若需將 HTML 內容完整傳遞給後端(含標籤、屬性):
// 前端:使用 encodeURIComponent 保護特殊字元
const encoded = encodeURIComponent(editor.getData());
// 傳送:$.post('/api/save', { content: encoded })
// 後端:解碼
String content = URLDecoder.decode(request.getParameter("content"), "UTF-8");
// 前端
const base64 = btoa(unescape(encodeURIComponent(editor.getData())));
// 後端 (Java)
byte[] decoded = Base64.getDecoder().decode(base64Str);
String content = new String(decoded, StandardCharsets.UTF_8);
| 場景 | 編碼 | 解碼 |
|---|---|---|
| URL 參數傳遞 | encodeURIComponent | decodeURIComponent |
| 表單提交 | 自動 (application/x-www-form-urlencoded) | 自動 |
| JSON 傳輸 | JSON.stringify (自動處理) | JSON.parse |
| Base64 傳輸 | btoa + encodeURIComponent | Base64 解碼 + decodeURIComponent |
textarea.innerHTML → value 解碼encodeURIComponent 或 JSON正確處理 HTML 實體編解碼,能避免資料遺失、XSS 風險與顯示異常。