How to convert characters to HTML entities using plain JavaScript?

Sometimes, we want to convert characters to HTML entities using plain JavaScript.

In this article, we’ll look at how to convert characters to HTML entities using plain JavaScript.

How to convert characters to HTML entities using plain JavaScript?

To convert characters to HTML entities using plain JavaScript, we use the string replace and charCodeAt methods.

For instance, we write

const html = text.replace(/[u00A0-u00FF]/g, (c) => {
  return "&#" + c.charCodeAt(0) + ";";
});

to call text.replace with a regex that matches the characters we want to replace.

We call it with a callback that returns the HTML entity equivalent of the character string c being replaced.

Conclusion

To convert characters to HTML entities using plain JavaScript, we use the string replace and charCodeAt methods.