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 https://stackblitz.com/edit/vanilla-js-html-encode)

 


Need Some Vanilla JS Help?

Search fiverr for freelance Vanilla JS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by