Avoiding split words when truncating text
In today’s world of widgets, dashboards and snippets, as programmers we often find ourselves truncating text.
I was doing some work on a classic asp website today and noticed the truncating was often mid-word.
This was my quick fix.
<% dim sp, txt sp = instr(10, rs("news_Text"), ".") txt = left(stripHTML(rs("Text")),sp) if sp 60 then sp = instr(50, rs("Text"), " ") if sp > 60 then sp = InStrRev(rs("Text"), " ",70) end if txt = trim(left(stripHTML(rs("Text")),sp)) & "..." end if response.Write(txt) %>
Basically;
- Look for period after the first 10 characters and if so, use that as our snippet.
- If the Period wasn’t found, or after 60 characters, check for a space (end-of-word) after 50 characters.
- If the space is greater than 60 characters, find the first space in reverse, starting at 70 characters.
Of course, this still leaves out a few possibilities, but suffices for input that has some relatively safe input validation. It could be beefed up easily with a few more safeguards in terms of 1) no spaces, 2) special characters, 3) check for space after period, e.g a.m or p.m., 4) other requirements based on what kind of text you may be truncating.
Cheers!
This entry was posted on August 21, 2009 at 3:48 pm and is filed under asp, optimization, web development with tags asp, mid-word, safeguard, snippet, text, truncate, widget. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a comment