Published: July 21 2023

Vanilla JS - HTML Encode in JavaScript

I do a lot of HTML encoding to include code samples in posts on this blog.

HTML encoding simply replaces HTML special characters like angle brackets (< and >) with HTML entities so they can be displayed as plain text in a web page.

JS HTML Encoding

I use this simple function to convert HTML code samples into text for blog posts.

It replaces just three special characters with their equivalent HTML entities:

  • & - &amp;
  • < - &lt;
  • > - &gt;
function htmlEncode(input) {
    return input
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');

StackBlitz Demo

Here's a demo of the HTML encode function in action on StackBlitz. The encoded field is auto updated as you type/paste text into the HTML field.

(See on StackBlitz at


Need Some Vanilla JS Help?

Search fiverr to find help quickly from experienced Vanilla JS freelance developers.

Follow me for updates

I share all new blog posts on Twitter and Facebook.

When I'm not coding

My wife and I are attempting to ride motorcycles around Australia and vlog about it on YouTube.


Supported by