function encodeToAmp(text) { var el = document.createElement("div"); el.textContent = text; el.innerText = text; return el.innerHTML; } encodeToAmp('&;'><"') // => &;'><"