Enhancing Readability with ASP - Trim the String
(Page 2 of 4 )
First, the string is trimmed, removing any whitespace at either end. If the string is actually longer than what you've specified as the maximum desired length, the whole string is returned. Otherwise, we move on in the function, trying to find the nearest space to the desired length. This is accomplished by employing ASP's inStrRev to search through the string in reverse. We give it the desired length, and that's where it starts searching, backwards. The reason for doing it backwards is that you'll only end up with a string slightly smaller than the desired length, but never larger.
If no space can be located, then we are forced to chop the string. Though this may not seem too desirable, we really have to do it, otherwise the string wouldn't be shortened at all. It shouldn't cause too much grief, as the only case where this would happen would be with long strings not containing words, as with serial numbers.
For most other string, this will work perfectly well. We use the character '…' because it produces the '...' in the width of only one ASCII character, and not three full periods. You can adjust this as you see fit.
A sample use of this would be:
strLong = " This string is too long! "
strTrimmed = NeatTrim( strLong, 13 )
response.write( strTrimmed )
This would produce:
This string...
Now, for the user's sake, it would be a good idea of somehow indicating what the full string really is. This can be done through the HTML 4.0 attribute of 'title'. Here's an example:
strLong = " This string is too long! "
strTrimmed = NeatTrim( strLong, 13 )
response.write( "<span title=""" & strLong & """>" & strTrimmed & "</span>" )
With that code, they will still see the neatly trimmed string, but when they move their mouse over it, they get the full string in the little 'title' popup. Now let's move onto the second.
Next: What Does 07/13/2004 Mean? >>
More ASP Articles
More By Justin Cook