AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=257&pId=-1
ChopLastWord Function
page
by Topher Jentoft
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 18704/ 21

Introduction
For the front page of the aspalliance.com site, we were trying to show a substring of article descriptions truncated after so many characters and then followed by "...more!" as a link for people to click to read the full article. Since I only wrote the thing using the VBScript "Left" function, it was indiscriminately cutting off the description in mid-word. This didn't really bother me too much, but it wasn't ideal. Well, it bothered one of our readers enough for them to do something about it, and so they sent in a function to truncate the description, but to ensure that no words are cut off.
Code

Below is the function that is used to accomplish this task:

' Copyrights (c) 2000, Martin Jansen
' This function chops the last word of a given string.
Function ChopLastWord( Line, Length )
 Dim S1, S2, I
 ChopLastWord = ""
 S1 = Left( Line, Length )
 S2 = Left( Line, Length )
 For I = Len(S1) to 1 step -1
  if Mid(S1,I,1) = " " then
   S2 = Left(S1,I)
   I = 0
  end if
 Next
 ChopLastWord = S2
End Function  
 

This function is used just like Left(), taking an input string and a length. The length is the maximum length that the result can be, but typically the result will be LESS than this length because it will chop off entire words until the full string is less than the provided length.

Alternative Code

Of course, there is always more than one way to skin a cat, especially when it comes to programming. Here's what Michael Brinkley had to offer that does the same thing with a lot less work:

Function truncLine(inputString,maxlength)
    If len(inputString) > maxlength Then
  inputString = left(inputString,maxlength)
  inputString = left(inputString,inStrRev(inputString," "))
    End If
    truncLine = inputString
End Function
 

Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-18 6:57:10 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search