Categories
JavaScript Answers

How to convert characters to HTML entities using plain JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *