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 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.