Categories
JavaScript Answers

How to convert special characters to HTML in JavaScript

Spread the love

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.

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 *