|
Displaying only the first 200 words of a long text field. (VB.Net) |
|
|
Written by: Justin Rich
Displaying only the first 200 words of a long text field.This is a article was written to show how the home page for this site will respond to new article postings. The site has been tweaked to give some verbage of the article up to 200 words (roughly), and I'm going to show you how we do it.
In order to limit the size of the article to 200 words, I simply do an IndexOf function that finds spaces, and then trims the left side of the string to the index of that 200th space. That particular function will not return a positive value if the string doesn't find a space, so some catching is required to make sure that the result is positive. If all is good, then we can just trim the string, but if not, then don't worry about it and leave the string as it was... because it means it's probably not 200 words.
Here's how we lay it out: (strMessage is the text field)
Dim intCount As Integer Dim intIndex As Integer
Do While intCount < 200 and intIndex > 0 intIndex = strMessage.IndexOf(" ", intIndex + 1) intCount += 1 Loop
If intIndex > 1 Then strMessage = Left(strMessage, intIndex)
Now if your using this for HTML content, then you will want to do some checking to make sure you're not interrupting any HTML blocks or, just like this site, since it involve code, that you're not interrupting a code block. For this site, if that 200'th space is inside the code block, I'm not going to want to start the code block rather than taking the risk that the code block is really long, and then having a much longer than 200 word string showing up on the home page.
For an example of how this works, the snipet above is the code driving the 10 most recent articles module on the home page. |
|
|
|
|
|