HFX Forum

Programming => Web Languages => Topic started by: Cobra on November 02, 2007, 06:36:33 AM

Title: Safe Truncating .NET VB
Post by: Cobra on November 02, 2007, 06:36:33 AM
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...
Title: Re:Safe Truncating .NET VB
Post by: Cobra on November 07, 2007, 05:13:49 AM
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 :)