You need to escape <
and &
. Escaping >
too doesn't hurt:
function magic(input) {
input = input.replace(/&/g, '&');
input = input.replace(/</g, '<');
input = input.replace(/>/g, '>');
return input;
}
Or you let the DOM engine do the dirty work for you (using jQuery because I'm lazy):
function magic(input) {
return $('<span>').text(input).html();
}
What this does is creating a dummy element, assigning your string as its textContent (i.e. no HTML-specific characters have side effects since it's just text) and then you retrieve the HTML content of that element - which is the text but with special characters converted to HTML entities in cases where it's necessary.
document.createTextNode(unsafestring);
Option
class'sinnerHTML
Ref: How to escape HTML