HTML Encoding Advanced

by May 9, 2017

The static .NET method HtmlEncode does a good job encoding the usual character codes but fails with many special characters. To encode all characters correctly, here is a function called ConvertTo-EncodedHtml:

function ConvertTo-EncodedHTML($HtmlText)
{
   
  $chars = [Web.HttpUtility]::HtmlEncode($HtmlText).ToCharArray()
  $txt = New-Object System.Text.StringBuilder
  $null = . {
      foreach($c in $chars)
      {
        if ([int]$c -gt 127) 
        {
          $txt.Append("&#" + [int]$c + ";")
        }
        else
        {
          $txt.Append($c)
        }
   }
   }
   return $txt.ToString()
}

This function checks all characters with ASCII code greater than 127 and converts these characters to encoded versions:

 
PS> Convert-EncodedHTML -HtmlText "A – s ‘Test’"
A – s  ‘Test’
 

Twitter This Tip! ReTweet this Tip!