C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
HtmlEncode: This method takes a string that is not encoded (like hasBrackets) and changes angle brackets to entity encodings.
HtmlDecode: This takes entity encodings (like gt and lt) and replaces them with their original char values, the opposite of HtmlEncode.
VB.NET program that uses HtmlEncode, HtmlDecode
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
Output
<b>Hi 'friend'</b>
<b>Hi 'friend'</b>
UrlEncode: This takes a normally-formatted string and replaces certain characters, like spaces and slashes, with encoded values.
UrlDecode: 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.
VB.NET program that uses UrlEncode, UrlDecode
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
Output
one+two%2Fthree
one two/three
However: The fastest way to encode HTML would be to make no changes. A system could simply not accept HTML chars.