Escape HTML in JavaScript (2025 Edition)
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:
const tests = ;
tests.;
gave: && got: &&
gave: "" got: ""
gave: '' got: ''
gave: << got: <<
gave: >> got: >>
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
.
// then
.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.
const characters = ;
characters.
character: && escaped: &&
character: "" escaped: ""
character: '' escaped: ''
character: << escaped: <<
character: >> escaped: >>
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
Endnotes
TIL that the there is a specific reason to use ' instead of '
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.