ASP 內建 Len 只能算字符數,無法區分中英文、處理多餘空白。本函數實現「中文算 2 字符、英文算 1、連續空白合併為一」的精準統計邏輯,適合標題截斷、內容摘要、字數限制場景。
<%
Function WordCount(strInput)
Dim strTemp, i, charCode, charWidth, totalWidth
If IsNull(strInput) Or strInput = "" Then
WordCount = 0
Exit Function
End If
' 1. 標準化空白符:Tab、換行、回車 → 空格
strTemp = Replace(strInput, vbTab, " ")
strTemp = Replace(strTemp, vbCr, " ")
strTemp = Replace(strTemp, vbLf, " ")
' 2. 去除首尾空格
strTemp = Trim(strTemp)
' 3. 合併連續空格為單一空格
Do While InStr(1, strTemp, " ", 1) <> 0
strTemp = Replace(strTemp, " ", " ")
Loop
' 4. 核心邏輯:逐字符判斷寬度
totalWidth = 0
For i = 1 To Len(strTemp)
charCode = AscW(Mid(strTemp, i, 1))
' 中日韓統一表意文字範圍:視為雙字節 (寬度 2)
If charCode > 255 Then
totalWidth = totalWidth + 2
Else
totalWidth = totalWidth + 1
End If
Next
' 5. 返回字符寬度總和 (可按需除以 2 得「中文詞數」)
WordCount = totalWidth
End Function
%>
<%
Dim testStr : testStr = "Hello 世界 這是測試" ' 含雙空格
Response.Write "原始長度:" & Len(testStr) & "<br>" ' 18
Response.Write "字符寬度:" & WordCount(testStr) & "<br>" ' 5*1 + 2*2 + 4*2 = 21
%>
AscW > 255 判定為雙字節字符 (中文、日文、韓文、全形符號)WordCount \ 2Function LeftByWidth(str, targetWidth)
Dim i, charCode, currentWidth, result
currentWidth = 0
result = ""
For i = 1 To Len(str)
charCode = AscW(Mid(str, i, 1))
If charCode > 255 Then currentWidth = currentWidth + 2 Else currentWidth = currentWidth + 1
If currentWidth > targetWidth Then Exit For
result = result & Mid(str, i, 1)
Next
LeftByWidth = result
End Function
這對函數組合可完美解決「標題顯示兩行、超出顯示省略號」等排版難題。