Vanilla JS – HTML Encode in JavaScript

Spread the love


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.

Table of Contents

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:

function htmlEncode(input) {
    return input
        .replace(/&/g, '&')
        .replace(//g, '>');
}

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





Share this content:

I am a passionate blogger with extensive experience in web design. As a seasoned YouTube SEO expert, I have helped numerous creators optimize their content for maximum visibility.

Leave a Comment