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 use the String.fromCharCode
method.
For instance, we write
const decodeHtmlCharCodes = (str) =>
str.replace(/(&#(\d+);)/g, (match, capture, charCode) =>
String.fromCharCode(charCode)
);
to define the decodeHtmlCharCodes
function.
In it, we call str.replace
with a regex to match all special characters with the regex.
The callback return the character given the charCode
, which we get from the regex matches.
Conclusion
To convert special characters to HTML in JavaScript, we use the String.fromCharCode
method.