home ~ socials ~ projects ~ rss

Escape HTML in JavaScript (2025 Edition)

August 2013

Same Old, Same Old

I published the first version of this post in 2013. It's now 2025. Figured it was worth looking to see if a way to escape HTML has been added to JavaScript in the past decade.

Nope1.

So, I'm back to doing this:

JavaScript
function escapeHTML(input) {
    return input
	.replaceAll(`&`, `&`)
	.replaceAll(`"`, `"`)
	.replaceAll(`'`, `'`)
	.replaceAll(`<`, `&lt;`)
	.replaceAll(`>`, `&gt;`);
}

const tests = [
  `&&`, `""`, `''`, `<<`, `>>`
];

tests.forEach((test) => {
    const out = [];
    const got = escapeHTML(test);
    out.push("gave:");
    out.push(test);
    out.push("got:");
    out.push(got);
    console.log(
	out.join(" ")
    )
});
Output:
gave: && got: &amp;&amp;
gave: "" got: &quot;&quot;
gave: '' got: &#39;&#39;
gave: << got: &lt;&lt;
gave: >> got: &gt;&gt;

The Little Differences

The big changed between this and my original code from 2013 is that I'm using .replaceAll() with a string inside it. The prior code used .replace() with a RegEx in it.

// now
.replaceAll(`&`, "")

// then
.replace(/&/g, "")

I've got no idea if it's an more or less efficient. Looks nicer though.

What Doesn't Work

The first thing I hit in my search was this answer from stackoverflow. It has the below function. Unfortunately, it doesn't work as expected.

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

const characters = [
  `&&`, `""`, `''`, `<<`, `>>`
];

characters.forEach((character) => {
    const escaped = escapeThatDoesNotWork(character);
    const out = [];
    out.push(`character:`);
    out.push(character);
    out.push(`escaped:`);
    out.push(escaped);
    console.log(
	out.join(" ")
    );
})
Output:
character: && escaped: &amp;&amp;
character: "" escaped: "" 
character: '' escaped: ''
character: << escaped: &lt;&lt; 
character: >> escaped: &gt;&gt;

The double quotes and apostrophes didn't get updated. That means it'll break if you tried to used the output from the function that has a double quote in it within an attribute.

I added a note to the answer in hopes that other folks don't get tripped up by it.

-a

end of line

Endnotes

TIL that the there is a specific reason to use &#39; instead of &apos;

See this post

It's from 2013. TBD on if it still applies. Better safe, regardless.

There's also this related answer that point to using the DOMParser.

I may look into that at some point, but the .replaceAll() function is working just fine for me for now.

References

This was the original answer I found in 2013. At the time it had ~170 upvotes. It's at 565 right now.

Footnotes

Unless I'm totally missing something.

Share link:
https://www.alanwsmith.com/en/01/81/kx/7t/?escape-html-in-javascript-2025-edition