Escaping Text Strings

by Feb 9, 2009

HTML on web pages uses tags and other special characters to define the page. To make sure text is not misinterpreted as HTML tags, you may want to escape text and automatically convert any ambiguous text character in an encoded format. Use EscapeDataString provided by the System.URI type to do just that:

function Escape-String($name) {
[System.Uri]::EscapeDataString($name)
}

Escape-String "Hello World"
Escape-String "<h1>Hello World</h1>"

To do the opposite and convert an encoded string back into the original representation, use UnescapeDataString():

[System.Uri]::UnescapeDataString("Hello%20World")

When working with web applications, you may want to escape characters so they are displayed correctly on the web.