在 VBScript 中,內建的 Trim 函數只能移除空白字元 (Space, ASCII 32)。若要移除字串前後的換行符號(如 vbLF、vbCr 或 vbCrLf),你需要使用正規表達式 (RegExp) 或手動循環檢查。
方法 1:使用正規表達式 (最推薦)
這是處理多種空白字元(包括空格、跳格 Tab、換行符號)最乾淨的方法。
vbs
Function TrimAll(strInput)
Dim objRegExp
Set objRegExp = New RegExp
' 模式說明:
' ^\s+ 匹配字串開頭的所有空白字元
' | 或
' \s+$ 匹配字串結尾的所有空白字元
objRegExp.Pattern = "^\s+|\s+$"
objRegExp.Global = True
TrimAll = objRegExp.Replace(strInput, "")
End Function
Function TrimAll(strInput)
Dim objRegExp
Set objRegExp = New RegExp
' 模式說明:
' ^\s+ 匹配字串開頭的所有空白字元
' | 或
' \s+$ 匹配字串結尾的所有空白字元
objRegExp.Pattern = "^\s+|\s+$"
objRegExp.Global = True
TrimAll = objRegExp.Replace(strInput, "")
End Function
' 測試
Dim myStr
myStr = vbLf & " Hello World " & vbLf
WScript.Echo "長度: " & Len(TrimAll(myStr)) ' 輸出將移除前後的換行與空格
沒有留言:
張貼留言