Converting Special Characters, Part 2

by Jul 22, 2014

All PowerShell versions

In a previous tip we illustrated how you can replace special characters in a text. Here is another approach that may be a bit slower but is easier to maintain. It also features a case-sensitive hash table:

function ConvertTo-PrettyText($Text)
{
  $hash = New-Object -TypeName HashTable

  $hash.'ä' = 'ae'
  $hash.'ö' = 'oe'
  $hash.'ü' = 'ue'
  $hash.'ß' = 'ss'
  $hash.'Ä' = 'Ae'
  $hash.'Ö' = 'Oe'
  $Hash.'Ü' = 'Ue'
    
  Foreach ($key in $hash.Keys)
  {
    $Text = $text.Replace($key, $hash.$key)
  }
  $Text
}

Note that the function won’t define a hash table via “@{}” but rather instantiates a HashTable object. While the hash table delivered by PowerShell is case-insensitive, the hash table created by the function is case-sensitive. That’s important because the function wants to differentiate between lower- and uppercase letters.

PS> ConvertTo-PrettyText -Text 'Mr. Össterßlim'
Mr. Oesstersslim

PS>  

To add replacements, simply add the appropriate “before”-character to the hash table, and make its replacement text its value.

If you’d rather specify ASCII codes, here is a variant that uses ASCII codes as key:

function ConvertTo-PrettyText($Text)   
{  
  $hash = @{
    228 = 'ae'
    246 = 'oe'
    252 = 'ue'
    223 = 'ss'
    196 = 'Ae'
    214 = 'Oe'
    220 = 'Ue'   
  }
  
  foreach($key in $hash.Keys)
  {
    $Text = $text.Replace([String][Char]$key, $hash.$key)
  }
  $Text
}

Twitter This Tip! ReTweet this Tip!