JavaScript HTML Encode Special Characters
Last Updated : Mar 11, 2024
IN - JavaScript | Written & Updated By - Riya
In this tutorial we will show you the solution of JavaScript html encode special characters, as many times we need to encode special characters in html, for example let we have to encode angle bracket that is < hence html may use it as opening tag but not as simple angle bracket.
As we may face more issues while using #,$,%,&,@, etc. let us solve this problem today.
Step By Step Guide On JavaScript Html Encode Special Characters :-
As, we say that many times we have to include special characters in our html codes and we face issue due to inbuilt interface of html.
So, there are many ways with help of which we can solve this issue. Whereas in this article we are going to use JavaScript to encode special characters in html.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> JavaScript html encode special characters</title> <script> function encode(string) { var i = string.length, array = []; while (i--) { var iC = string[i].charCodeAt(); if (iC < 65 || iC > 127 || (iC > 90 && iC < 97)) { array[i] = '' + iC + ';'; } else { array[i] = string[i]; } } return array.join(''); } </script> </head> <body style=”text-align:center”> <script> document.write(encode("If b<a and a<h then b<h")); </script> </body> </html>
- First, we write <! DOCTYPE html> which we used as an instruction to the web browser about what version of HTML file is written in.
- Secondly, the <html> tag is used to indicate the beginning of an HTML document.
- As above now <head> tag is used to contain information about web page. In this tag a <title> tag is used which helps us to specify a webpage title. Both <head> and <title> tags are Paired tags. So, both have </head> and </title> ending tags respectively.
- Here, then we create a body tag. All the content which we want to show on browser’s screen or display is always written inside this codes.
- Here, as you see in body we use document.write to print the string or say line which we want to print. But here we use encode function which is user defined function and created inside head. Let us understand this first.
- Here, as you can see we convert our special characters to html specific codes. And inside the script we use replaceAll the special characters with regular html expressions. We hope that you understand these lines of codes properly with help of these steps.
- At last, the <body> and <html> tags are closed with </body> and </html> respectively.
Conclusion :-
At last in conclusion, here we can say that with the help of this article we are able to understand how to convert an object to array using JavaScript.
I hope this tutorial on JavaScript html encode special characters helps you and the steps and method mentioned above are easy to follow and implement.