前端常需從富文本中提取純文本,或保留特定標籤。掌握正則模式能高效處理。
const stripAllTags = (html) => html.replace(/<[^>]*>/g, '');
解析:<[^>]*> 匹配從 < 到 > 的任意字符(貪婪模式)。
// 僅保留 br、img、p 標籤
const keepSomeTags = (html) => html.replace(/<(?!(\/?(br|img|p)\b))[^>]*>/gi, '');
解析:負向前瞻 (?!...) 排除指定標籤。\/? 匹配可選關閉斜線,\b 詞邊界防止誤匹配 pre 等。
function filterHtmlTags(html, allowedTags = []) {
if (!allowedTags.length) return html.replace(/<[^>]*>/g, '');
const escaped = allowedTags.map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
const regex = new RegExp(`<(?!\\/?(${escaped})\\b)[^>]*>`, 'gi');
return html.replace(regex, '');
}
// 使用範例
const dirty = '<div><p>保留</p><script>alert(1)</script><br/></div>';
console.log(filterHtmlTags(dirty, ['p', 'br']));
// 輸出: "<p>保留</p><br/>"
單純正則無法完整解析巢狀結構、屬性值中的 >、註釋、CDATA 等邊界情況。生產環境建議:
DOMParser 解析後遍歷節點<.*> 錯,應用 <[^>]*> 或 <.*?><!-- -->、Doctype、CDATA 區塊> 字符(如 <div data="a>b">)導致提前截斷<br/>、<img/> 需正確匹配正則適合簡單場景,複雜 HTML 清洗請使用 DOM 方案。