Categories
JavaScript Answers

How to encode HTML entities in JavaScript?

Spread the love

Sometimes, we want to encode HTML entities in JavaScript.

In this article, we’ll look at how to encode HTML entities in JavaScript.

How to encode HTML entities in JavaScript? To encode HTML entities in JavaScript, we use the charCodeAt method.

For instance, we write

const encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/g, (i) => {
  return "&#" + i.charCodeAt(0) + ";";
});

to call the rawStr.replace method with the regex that matches the HTML entities.

Then we encode them by replacing them with “&#” + i.charCodeAt(0) + “;”;.

The g flag replace all matches.

Conclusion

To encode HTML entities in JavaScript, we use the charCodeAt method.

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 *