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;

  1. Look for period after the first 10 characters and if so, use that as our snippet.
  2. If the Period wasn’t found, or after 60 characters, check for a space (end-of-word) after 50 characters.
  3. 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!

Leave a comment