views:

27

answers:

2

I want to, in vbScript (Classic ASP), parse a string to a specified length without cutting words. The final string may be less than the specified length (to avoid cutting words), but should not exceed it..

A: 

Assuming you're break words on a space.

startIndex = 0
index = 1
do while len(inputString) - startIndex > desiredLength
    tmp = mid(inputString, 0, desiredLength)
    outputStrings[index] = left(tmp, instrrev(tmp, " ")-1)
    startIndex = startIndex + len(outputStrings[index]) + 1
    index = index + 1
loop 
Andrew Cooper
A: 

@Caveatrob: Also assuming you break on spaces:

<%  
Option Explicit  

Function TrimIt(sInput, iLength)  
    Dim aWords, iCounter, sOutput, sTmp  

    sOutput = sInput  

    If InStr(sInput, " ") > 0 Then  
        aWords = Split(sInput, " ")  
        For iCounter = 0 To UBound(aWords)  
            If Len(aWords(iCounter) & " ") + Len(sTmp) <= iLength Then  
                sTmp = sTmp & " " & aWords(iCounter)  
            Else  
                Exit For  
            End If  
        Next  
        sOutput = sTmp  
    End If  

    TrimIt = sOutput  
End Function  

Response.Write TrimIt("This works slightly better", 11)  
%>  
stealthyninja