Categories
JavaScript Answers

How to encode HTML entities in JavaScript?

Spread the love

To encode HTML entities in JavaScript, we can use the string replace and charCodeAt methods.

For instance, we write

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

to call replace with a regex pattern that we want to look for in rawStr and a callback does the replacement.

In the callback, we get each result and replace them with the HTML entity with the character code that we get with i.charCodeAt(0).

We prepend "&#" and append ';' to the character code to form the entity.

Conclusion

To encode HTML entities in JavaScript, we can 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 *