Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to convert special characters to HTML in Javascript?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In HTML there are many cases in which the browser gets confused while rendering the page. In HTML the less-than sign ( < ) means the opening of some tag and if we place an element an after it like ‘a’ or ‘h’ then browser identifies them as an anchor and heading tab respectively. Similar is the case with some special character including less than, at the rate (@), front and backslash, etc.

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




<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>
  
<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>
  
<head>
    <script>
        function Encode(string) {
            var i = string.length,
                a = [];
  
            while (i--) {
                var 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>
</head>
  
<body>
    <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

My Personal Notes arrow_drop_up
Last Updated : 27 Sep, 2019
Like Article
Save Article
Similar Reads
Related Tutorials