Safe Truncating .NET VB

Started by Cobra, November 02, 2007, 06:36:33 AM

Previous topic - Next topic
November 02, 2007, 06:36:33 AM Last Edit: January 09, 2015, 12:56:32 PM by Tazinator
Thought i'd throw up another small yet useful function for ya...

This function will allow you to specify the string length you need.. And NO SubString wont do the same, because if your string length is less than specified in the SubString your application wont run.

So anyway.. this will truncate the string to the length you want, if the strings char length is less that you specified it will use the string length instead...

Also when truncating from user defined input you need to be WELL aware that if the user is putting input into the site via a CMS with a WYSIWYG then chances are there are now HTML tags in your content... So when you truncate you could be left with open HTML tags.. so this function will also strip out any HTML and use the sites predefined CSS
Code  VB Select
Public Shared Function TruncateString(ByVal OriginalString As String, ByVal StringLen As Integer )
          
         Dim rawString As String
         
         If OriginalString <> "" Then
            rawString = Regex.Replace(OriginalString, "<(.|\n)+?>", String.Empty)
         End If
         
         Dim RawStringLen As Integer = Len(rawString)
         Dim RequestedLen As Integer
         
          if RawStringLen > StringLen then 
             RequestedLen = StringLen
          else 
             RequestedLen = RawStringLen
          end if 

         Dim finalString = rawString.SubString(0, RequestedLen)
         
         return finalString   
   
End Function


Nothing fancy but it should help a little...
I am not suffering with insanity... I am loving every minute of it.

November 07, 2007, 05:13:49 AM #1 Last Edit: January 09, 2015, 12:56:47 PM by Tazinator
Update to this function.. It wasn't handling nulls correctly AT ALL!! haha ..

Code  VB Select
Public Shared Function TruncateString(ByVal OriginalString As Object, ByVal StringLen As Integer )
          
         if IsDBnull(OriginalString) then 
            return("")
         end if
         
         Dim rawString As String
         
         If OriginalString <> "" Then
            rawString = Regex.Replace(OriginalString, "<(.|\n)+?>", String.Empty)
         End If
         
         Dim RawStringLen As Integer = Len(rawString)
         Dim RequestedLen As Integer
         
          if RawStringLen > StringLen then 
             RequestedLen = StringLen
          else 
             RequestedLen = RawStringLen
          end if 

         Dim finalString = rawString.SubString(0, RequestedLen)
         
         return finalString   
   
      End Function


That'll do it :)
I am not suffering with insanity... I am loving every minute of it.

SMF spam blocked by CleanTalk