ASP 提供三個去除空格函數,適用場景不同:
| 函數 | 功能 | 範例輸入 | 輸出結果 |
|---|---|---|---|
| Trim(str) | 同時移除首尾空格 | " hello world " | "hello world" |
| LTrim(str) | 僅移除左側空格 | " hello world " | "hello world " |
| RTrim(str) | 僅移除右側空格 | " hello world " | " hello world" |
<%
Dim txt
txt = " www.example.com is a beautiful day! "
Response.Write "Trim: [" & Trim(txt) & "]<br/>"
Response.Write "LTrim: [" & LTrim(txt) & "]<br/>"
Response.Write "RTrim: [" & RTrim(txt) & "]<br/>"
%>
內建函數無法移除字串中間的空格,需結合 Replace:
Function RemoveAllSpaces(str)
RemoveAllSpaces = Replace(str, " ", "")
End Function
去除空格常用於 SQL 注入防禦的前置處理,但不能替代參數化查詢。建議採用:
Trim 能移除中間空格 → 需用 ReplaceTrim 結果拼接 SQL → 仍有注入風險Replace(str, " ", "")掌握三大函數差異,配合 Replace 與正則表達式,即可靈活處理各類字串清洗需求。