Traditional Escaping
If you're using XHTML, you'll need to use a CDATA
section. You can use these in HTML, too, but HTML isn't as strict.
I split up the string constants so that this code will work inline on XHTML within CDATA blocks. If you are sourcing your JavaScript as separate files, then you don't need to bother with that. Note that if you are using XHTML with inline JavaScript, then you need to enclose your code in a CDATA block, or some of this will not work. You will run into odd, subtle errors.
function htmlentities(text) {
var escaped = text.replace(/\]\]>/g, ']]' + '>]]><' + '![CDATA[');
return '<' + '![CDATA[' + escaped + ']]' + '>';
}
DOM Text Node
The "proper" way to escape text is to use the DOM function document.createTextNode
. This doesn't actually escape the text; it just tells the browser to create a text element, which is inherently unparsed. You have to be willing to use the DOM for this method to work, however: that is, you have use methods such as appendChild
, as opposed to the innerHTML
property and similar. This would fill an element with ID an-element
with text, which would not be parsed as (X)HTML:
var textNode = document.createTextNode("<strong>This won't be bold. The tags " +
"will be visible.</strong>");
document.getElementById('an-element').appendChild(textNode);
jQuery DOM Wrapper
jQuery provides a handy wrapper for createTextNode
named text
. It's quite convenient. Here's the same functionality using jQuery:
$('#an-element').text("<strong>This won't be bold. The tags will be " +
"visible.</strong>");