FCC Bonfire Series 128: Convert HTML Entities

This next bonfire will prove useful in the future (you’ll see why when the time comes). We are going to be converting special characters to their HTML entity counterparts.

What is a HTML entity you may ask, you see, some characters have special meanings in HTML, the greater than and lesser than symbols (>, <) for example, are used in HTML tags, and the browser can confuse them if used in plain text. For this reason, these kind of characters should be written as their HTML entity (or entities, each character may be written in a few ways). For example:

  • & -> &amp;
  •  -> &quot;

You can check out the whole list here.

The bonfire will have us replace the following characters (you can take a look at their HTML entity codes in the like above):

  • &
  • <
  • >

We are JavaScript wizards. We got this under control. We know the HTML entity codes, we know the tools JavaScript has to offer. Come on, let’s get to it!

As you might have guessed, we are going to be using the replace method available to strings., we will concatenate this method and replace special characters one by one, returning the result at the end:

function convert(str) {
  return str.replace(/&/g, '&amp;').replace(/'/g, ''').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

As you can see, I used a replace after another, getting our characters converted. Good luck on your road to code efficiency!