Programming > Web Languages
Safe Truncating .NET VB
(1/1)
Cobra:
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
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...
Cobra:
Update to this function.. It wasn't handling nulls correctly AT ALL!! haha ..
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 :)
Navigation
[0] Message Index
Go to full version