HtmlEncode and HtmlDecode
This page was last reviewed on Oct 11, 2023.
Dot Net Perls
HtmlEncode, Decode. HTML strings reserve certain characters, angle brackets, for markup. These chars must be encoded to exist in valid HTML.
Urls, meanwhile, require certain characters like spaces use url encoding (a code preceded by a percentage sign). With WebUtility—HtmlEncode and UrlEncode—we encode these ways.
HtmlEncode, HtmlDecode. This example handles HTML. The first string "input" contains HTML tags, but we want to represent these as text in an HTML page.
Note HtmlEncode takes a string that is not encoded and changes angle brackets to entity encodings.
Note 2 HtmlDecode takes entity encodings (like gt and lt) and replaces them with their original char values, the opposite of HtmlEncode.
Imports System.Net Module Module1 Sub Main() Dim input As String = "<b>Hi 'friend'</b>" ' Encode it. Dim result1 As String = WebUtility.HtmlEncode(input) ' Decode it back again. Dim result2 As String = WebUtility.HtmlDecode(result1) ' Write results. Console.WriteLine(result1) Console.WriteLine(result2) End Sub End Module
&lt;b&gt;Hi &#39;friend&#39;&lt;/b&gt; <b>Hi 'friend'</b>
UrlEncode, UrlDecode. These methods work in a similar way as the HTML-encoding ones. We first use an Imports System.Net directive at the top.
Detail This takes a normally-formatted string and replaces certain characters, like spaces and slashes, with encoded values.
Detail This converts back an encoded url into a normal string. The two methods will round-trip data.
Tip With UrlEncode, we should only pass part of the url, not the scheme, as http:// will be changed in an undesirable way.
Imports System.Net Module Module1 Sub Main() ' This string contains space and slash. Dim hasSpaces As String = "one two/three" ' Encode it as url. Dim result1 As String = WebUtility.UrlEncode(hasSpaces) Dim result2 As String = WebUtility.UrlDecode(result1) ' Example's results. Console.WriteLine(result1) Console.WriteLine(result2) End Sub End Module
one+two%2Fthree one two/three
Performance. In my testing, the HtmlEncode and HtmlDecode methods are faster than approaches that use String Replace (which may cause excess allocations).
String Replace
However The fastest way to encode HTML would be to make no changes. A system could simply not accept HTML chars.
A summary. With these encoding methods, we can process pages and urls in VB.NET to make them valid. This will prevent browsers from incorrectly rendering a site or any HTML interface.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 11, 2023 (edit).
© 2007-2024 Sam Allen.