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.
Here's the code:
As said we use the InStrRev function to be sure the word is not truncated.
If we change the lenght to 14 (just to understand the logic of the function), the result will be:
Hope you find the example useful. As usual let me know if you need more help.
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.