Showing posts with label Escape HTML. Show all posts
Showing posts with label Escape HTML. Show all posts

Saturday, July 25, 2009

Web: HTML Encoder

This page will convert HTML special characters into HTML entities. The encoded text can then be inserted into another HTML document or blog posting and the reserved characters (such as < and &) will show up normally.

Enter your text in the form field below. The encoded result will be displayed in the lower field as you type.

Enter HTML to Encode:


HTML Encoded Result: (Click to Select All)

The HTML encoding is performed with this Javascript function:

/* encode html entities */
var char2entity = { '"' : '&quot;', '<' : '&lt;', '>' : '&gt;', '&' : '&amp;', "'" : '&#39;' }; /* IE can't handle &apos; */
function encode_entities(str) {
var rv = '';
for (var i = 0; i < str.length; i++) {
var ch = str.charAt(i);
rv += char2entity[ch] || ch;
}
return rv;
}
See also: handy shell function for html encoding.

Keywords: html encoding, html encoder

Saturday, July 11, 2009

Shell: Aliases for Encoding/Decoding HTML Strings

Here are a couple of simple Unix aliases for quickly encoding and decoding HTML strings. I have these defined in my ~/.bash_aliases file.

alias htmlencode="perl -MHTML::Entities -pe 'encode_entities(\$_)'"
alias htmldecode="perl -MHTML::Entities -pe 'decode_entities(\$_)'"
To encode/escape all unsafe characters in a string with their HTML entities:

$ echo "This is <b>bold</b>" | htmlencode
This is &lt;b&gt;bold&lt;/b&gt;
And to decode/unescape HTML entities:

$ echo "This is &lt;b&gt;bold&lt;/b&gt;" | htmldecode
This is bold
These aliases depend on Perl and the HTML::Entities module which are standard on most modern Unixes.

See also: Web-based HTML encoder.