How to encode a string in JavaScript for displaying in HTML? [duplicate]

Solution 1:

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

So then with var unsafestring = "<oohlook&atme>"; you would use htmlEntities(unsafestring);

Solution 2:

Do not bother with encoding. Use a text node instead. Data in text node is guaranteed to be treated as text.

document.body.appendChild(document.createTextNode("Your&funky<text>here"))