Open In App

How to Convert Special Characters to HTML in JavaScript?

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, special characters like less-than (<), greater-than (>), and others can cause rendering issues in HTML because they are interpreted as tags.

To display these characters correctly in HTML, it’s necessary to convert them into their respective HTML entities. This process prevents the browser from misinterpreting them as HTML tags.

JavaScript can be used to automate the conversion of special characters into safe HTML entities, ensuring proper rendering of text that includes symbols like <, >, &, and others.

Example: This example is an illustration of the problem caused when the HTML text is not converted to the special format.

HTML
<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <div>
        If b<a and a<h then b<h. <!-- the browser understands it as anchor
            tag-->
    </div>
</body>

</html>


The part b<a is problematic. The browser understands it as anchor tags. Similar is the case with b<h

Output:

If b

Solution 1:

One way to solve it is to manually by putting special symbols in the pace of the respective special character which is problematic. But for very heavy websites it is very difficult to draw all the characters and then render it in HTML.

HTML
<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <div>
        If b
        < a and ab < h then b < h. <!-- the browser understands it as less
            than-->
    </div>
</body>

</html>

Output:

If b < a and ab < h then b < h.

JavaScript based Solution:

One another way is to convert each special character to its respective HTML code using javascript. Within the script we will replace all the special charters with the help of a regular expression which is “&#” + ASCII value of character + “;”. We apply the same rule with all the text on the page.

HTML
<!DOCTYPE html>
<html>

<head>

</head>

<body>
    <script>
        function Encode(string) {
            let i = string.length,
                a = [];

            while (i--) {
                let iC = string[i].charCodeAt();
                if (iC < 65 || iC > 127 || (iC > 90 && iC < 97)) {
                    a[i] = '&#' + iC + ';';
                } else {
                    a[i] = string[i];
                }
            }
            return a.join('');
        }
    </script>
    <script>
        document.write(Encode("If b<a and a<h then b<h"));
    </script>
</body>

</html>

Output:

If b<a and a<h then b<h


Article Tags :

Similar Reads