Monday, 24 October 2011

ASP: how to create an excerpt from a text string

   


In the following short article, we are going to build a function which will extract an excerpt from a text string, using classic ASP. The function could be used in blogs, or in general, when we need to display just a part of an article, a news or any long text (maybe providing a link to the complete piece of text).

The function is very simple, but it has a little trick in it: it won't cut a word. Basically we are going to benefit from the InStrRev VBScript function.

Let's see the how we do it.


The function
As said our excerpt function is very simple. In order to use it, we need to pass it two variables: the text to be cut  and the lenght of output.
Here's the code:
<%
function excerpt(strIn,strLen)
   strOut = trim(strIn)

   if strLen < len(strIn) then
      strOut = left(strIn,strLen)
      if instrrev(strOut," ") then
         strOut= left(strOut,instrrev(strOut," "))
      end if
      excerpt = strOut & "..."
   end if

end function
%>
The two aforementioned variables are strIn and strLen. The result is strOut.
As said we use the InStrRev function to be sure the word is not truncated.

The use and the result
If we use the function like:
<%=excerpt("This is a very long text", 15)%>
The result will be:
This is a very ... 

If we change the lenght to 14 (just to understand the logic of the function), the result will be:
This is a ...

Hope you find the example useful. As usual let me know if you need more help.

3 comments:

  1. I needed to run the exerpt through a code stripping function before this one.
    If your StrIn contains HTML code then it may be cut off midway and your HTML code will be shown (in part).

    Eg: Hello I am some text text</p...

    ReplyDelete
    Replies
    1. Ben,
      thanks for the remark. What you say is correct: the input string should be only text. In order to avoid the problem, you should use a Replace function, stripping all the HTML tags from the StrIn.

      Delete
  2. If strIn value is less than strLen value the result is null. To fix, replace it with the complete condition:

    Function excerpt(strIn,strLen)
    strOut = trim(strIn)
    If strLen < len(strIn) Then
    strOut = left(strIn,strLen)
    If instrrev(strOut," ") Then
    strOut= left(strOut,instrrev(strOut," "))
    End If
    excerpt = strOut & "..."
    Else
    excerpt = strIn
    End If
    End Function

    ReplyDelete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.