Sometimes, we want to convert special characters to HTML in JavaScript.
In this article, we’ll look at how to convert special characters to HTML in JavaScript.
How to convert special characters to HTML in JavaScript?
To convert special characters to HTML in JavaScript, we can us the String.fromCharcode
method.
For instance, we write
const decodeHtmlCharCodes = (str) =>
str.replace(/(&#(\d+);)/g, (match, capture, charCode) =>
String.fromCharCode(charCode)
);
console.log(decodeHtmlCharCodes("’"));
to create the decodeHtmlCharCodes
function that calls str.replace
with a regex to match all HTML entities with /(&#(\d+);)/g
.
And we replace them all with the character that’s returned from String.fromCharCode(charCode)
.
The charCode
in the callback is the character code of the whole HTML entity.
Conclusion
To convert special characters to HTML in JavaScript, we can us the String.fromCharcode
method.