| 方法 | 核心技術 | 特點 | 適用場景 |
|---|---|---|---|
| 1. HTML Encode/Decode | 字元實體替換 | 不移除標籤,轉義顯示原始碼 | 內容安全顯示、程式碼展示 |
2. RegExp 移除 <...> | 正則 <[^>]*> | 簡單快速、可能誤傷 < 符號 | 簡單過濾、效能優先 |
3. RegExp 非貪婪匹配 <.+?> | 正則 <.+?> + 迴圈替換 | 較精準處理巢狀/屬性 | 一般內容淨化 |
| 4. 分開匹配開/閉標籤 | 兩階段正則 <[^<]*> + </[^<]*> | 嘗試處理不完整標籤 | 髒資料清洗 |
function htmlEncode(text) {
return text.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(//g, '>');
}
function htmlDecode(text) {
return text.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
Function NoHTML(str)
Dim re
Set re = New RegExp
re.IgnoreCase = True
re.Global = True
re.Pattern = "<[^>]*>" ' 匹配 <...>
NoHTML = re.Replace(str, "")
Set re = Nothing
End Function
Function FilterHTML(strToFilter)
Dim objRegExp, match, matches
Set objRegExp = New RegExp
objRegExp.IgnoreCase = True
objRegExp.Global = True
objRegExp.Pattern = "<.+?>" ' 非貪婪匹配
Set matches = objRegExp.Execute(strToFilter)
For Each match In matches
strToFilter = Replace(strToFilter, match.Value, "")
Next
FilterHTML = strToFilter
Set objRegExp = Nothing
End Function
Function NoHTML(str)
Dim re
Set re = New RegExp
re.IgnoreCase = True
re.Global = True
' 先移除開啟標籤
re.Pattern = "<[^<]*>"
str = re.Replace(str, "")
' 再移除關閉標籤
re.Pattern = "[^<]*>"
str = re.Replace(str, "")
NoHTML = str
Set re = Nothing
End Function
Function SafeHTML(str, allowedTags)
' allowedTags 如 "b,i,u,br,p,img"
Dim re, tags, tag, pattern
Set re = New RegExp
re.IgnoreCase = True
re.Global = True
tags = Split(allowedTags, ",")
For Each tag In tags
' 保留該標籤:先佔位符保護
str = Replace(str, "<" & tag & ">", "[[KEEP_" & tag & "]]")
str = Replace(str, "" & tag & ">", "[[KEEP_/" & tag & "]]")
' 處理帶屬性
re.Pattern = "<\s*" & tag & "\b[^>]*>"
str = re.Replace(str, "[[KEEP_" & tag & "_ATTR]]")
Next
' 移除所有其他標籤
re.Pattern = "<[^>]*>"
str = re.Replace(str, "")
' 還原保留標籤
For Each tag In tags
str = Replace(str, "[[KEEP_" & tag & "]]", "<" & tag & ">")
str = Replace(str, "[[KEEP_/" & tag & "]]", "" & tag & ">")
str = Replace(str, "[[KEEP_" & tag & "_ATTR]]", "<" & tag & ">") ' 簡化:屬性丟失
Next
SafeHTML = str
End Function
onclick) 等極難完全處理四大方法各有取捨,簡單場景用方法二/三,需顯示原始碼用方法一,複雜安全需求請引入專業函式庫。