在伺服器端(ASP/VBScript)或客戶端需要移除 HTML 標籤、僅保留純文字時,正則表達式是最直接的工具。本文提供完整的 VBScript 函式 stripHTML,示範如何移除標籤、轉義實體字元,並附上測試表單頁面。
<%
Option Explicit
Function stripHTML(strHTML)
' 移除 HTML 標籤,回傳純文字
Dim objRegExp, strOutput
Set objRegExp = New RegExp
objRegExp.IgnoreCase = True
objRegExp.Global = True
objRegExp.Pattern = "<.+?>" ' 非貪婪匹配所有標籤
' 替換標籤為空字串
strOutput = objRegExp.Replace(strHTML, "")
' 轉義殘留的 < > 實體
strOutput = Replace(strOutput, "<", "<")
strOutput = Replace(strOutput, ">", ">")
Set objRegExp = Nothing
stripHTML = strOutput
End Function
%>
<form method="post" id="form1" name="form1">
<b>Enter an HTML String:</b><br>
<textarea name="txtHTML" cols="50" rows="8" wrap="virtual"><%=Request("txtHTML")%></textarea>
<p>
<input type="submit" value="Strip HTML Tags!" id="submit1" name="submit1">
</form>
<% If Len(Request("txtHTML")) > 0 Then %>
<p><hr><p>
<b><u>View of string <i>with no</i> HTML stripping:</u></b><br>
<xmp><%=Request("txtHTML")%></xmp><p>
<b><u>View of string <i>with</i> HTML stripping:</u></b><br>
<pre><%=StripHTML(Request("txtHTML"))%></pre>
<% End If %>
<.+?>:非貪婪匹配 < 到最近的 >,涵蓋單標籤(<br>)、雙標籤(<div>...</div>)、帶屬性標籤。IgnoreCase = True:大小寫不敏感,匹配 <DIV> 等。Global = True:全域替換所有匹配。| 問題 | 說明 | 改進建議 |
|---|---|---|
| Script/Style 內容未移除 | 正則會保留 <script>code</script> 中的 code | 先以 <script[\s\S]*?</script> 移除再跑主正則 |
| 註解未移除 | <!-- comment --> 會被保留 | 加入 <!--[\s\S]*?--> 模式 |
| 條件註釋 | IE 條件註釋 <![if IE]>...<![endif]> 未處理 | 加入專用模式或使用 HTML 解析器 |
| 編碼實體未解碼 | , & 等保持原樣 | 配合 Server.HTMLDecode 或實體對照表解碼 |
| 巢狀標籤邊界 | 極複雜巢狀可能誤判 | 嚴謹場景請用 DOMParser (客戶端) 或 HTML Agility Pack (伺服端 .NET) |
function stripHTML(str) {
const div = document.createElement('div');
div.innerHTML = str;
return div.textContent || div.innerText || '';
}
// 或使用 DOMParser(支援 SVG/MathML)
function stripHTML2(str) {
const doc = new DOMParser().parseFromString(str, 'text/html');
return doc.body.textContent || '';
}
現代專案強烈建議使用瀏覽器原生 DOM 解析而非正則,正確率 100% 且自動處理實體解碼、巢狀結構、XSS 風險。