How to escape HTML

I’m very surprised no one answered this. You can just use the browser it self to do the escaping for you. No regex is better or safer than letting the browser do what it does best, handle HTML.

function escapeHTML(str){
    var p = document.createElement("p");
    p.appendChild(document.createTextNode(str));
    return p.innerHTML;
}

or a short alternative using the Option() constructor

function escapeHTML(str){
    return new Option(str).innerHTML;
}

Leave a Comment