VBScript 內建 Len/Left/Right 以 **位元組** 計算,中文字佔 2 位元組導致視覺長度錯誤。本文提供三個函數,依據 Asc 判斷字元是否為雙位元組 (中文/全形),以「字元寬度」計算長度與截取,完美替代內建函數。
Function StrLength(Str)
Dim Temp_Str, I, Test_Str
Temp_Str = Len(Str)
StrLength = 0
For I = 1 To Temp_Str
Test_Str = Mid(Str, I, 1)
If Asc(Test_Str) > 0 Then
StrLength = StrLength + 1 ' ASCII (0-127) 視為 1
Else
StrLength = StrLength + 2 ' 雙位元組字元視為 2
End If
Next
End Function
Function StrLeft(Str, L)
Dim Temp_Str, I, Test_Str, lens
Temp_Str = Len(Str)
StrLeft = ""
lens = 0
For I = 1 To Temp_Str
Test_Str = Mid(Str, I, 1)
StrLeft = StrLeft & Test_Str
If Asc(Test_Str) > 0 Then lens = lens + 1 Else lens = lens + 2
If lens >= L Then Exit For
Next
End Function
Function StrRight(Str, L)
Dim Temp_Str, I, Test_Str, lens
Temp_Str = Len(Str)
StrRight = ""
lens = 0
For I = Temp_Str To 1 Step -1
Test_Str = Mid(Str, I, 1)
StrRight = Test_Str & StrRight
If Asc(Test_Str) > 0 Then lens = lens + 1 Else lens = lens + 2
If lens >= L Then Exit For
Next
End Function
Dim s
s = "ABC中文123"
Response.Write "Len=" & Len(s) & " StrLen=" & StrLength(s) & "
"
' Len=10 StrLen=13 (3中文*2 + 7英文*1)
Response.Write StrLeft(s, 8) & "
" ' ABC中文1 (寬度 3+2*2+1=8)
Response.Write StrRight(s, 8) & "
" ' 中文123 (寬度 2*2+3=7? 實際從右算)
函數內使用變數 I 作為迴圈計數器,**若呼叫端也在使用 I 當迴圈變數**,會導致外層迴圈異常。建議:
iLoop、idx 等獨特名稱。I。若環境支援 VBScript.RegExp,可用正則 (?:[^\x00-\x7F]|[\x00-\x7F]){n} 截取,或升級 ASP.NET 使用 StringInfo 類別正確處理 Unicode 字素叢集 (Grapheme Clusters)。