Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to convert Unicode values to characters in JavaScript ?
Next article icon

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

Next Article
How to convert Unicode values to characters in JavaScript ?
author
piyush25pv
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How to Convert Special HTML Entities Back to Characters in PHP?
    Sometimes, when we work with HTML in PHP, you may encounter special characters that are represented using HTML entities. These entities start with an ampersand (&) and end with a semicolon (;). For example, &lt; represents <, &gt; represents >, and &amp; represents &. To co
    1 min read
  • How to Convert HTML to JSON in JavaScript ?
    Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript. Below are the approaches to convert html to JSON in JavaScript: Table of Content Using html-to-json Lib
    2 min read
  • How to convert Unicode values to characters in JavaScript ?
    The purpose of this article is to get the characters of Unicode values by using JavaScript String.fromCharCode() method. This method is used to return the characters indicating the Unicode values. Description: Unicode is a character encoding standard that assigns a unique number to every character,
    2 min read
  • How to Convert String to Camel Case in JavaScript?
    We will be given a string and we have to convert it into the camel case. In this case, the first character of the string is converted into lowercase, and other characters after space will be converted into uppercase characters. These camel case strings are used in creating a variable that has meanin
    4 min read
  • How to escape & unescape HTML characters in string in JavaScript?
    Escaping and unescaping HTML characters is important in JavaScript because it ensures proper rendering of content, preventing HTML injection attacks and preserving text formatting when displaying user-generated or dynamic content on web pages. Escape HTML Characters< : &lt;> : &gt;" :
    3 min read
  • How to Convert JSON to base64 in JavaScript ?
    Base 64 is the encoding scheme that represents binary data in a printable ASCII format, commonly used for data serialization and transmission. Table of Content Using btoa functionUsing Manual ConversionUsing btoa functionIn this approach, we're using btoa to encode a UTF-8 string representation of a
    2 min read
  • How to convert hyphens to camel case in JavaScript ?
    Given a string containing hyphens (-) and the task is to convert hyphens (-) into camel case of a string using JavaScript. Approach: Store the string containing hyphens into a variable.Then use the RegExp to replace the hyphens and make the first letter of words upperCase. Example 1: This example co
    2 min read
  • How to Convert Integer to Its Character Equivalent in JavaScript?
    In this article, we will see how to convert an integer to its character equivalent using JavaScript. Method Used: fromCharCode()This method is used to create a string from a given sequence of Unicode (Ascii is the part of Unicode). This method returns a string, not a string object. C/C++ Code let s
    2 min read
  • How To Convert Base64 to JSON String in JavaScript?
    There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format. It generally happens when one has to transmit data over the network where Base64 encoding is well suited for encoding binary data. In this article, we will s
    2 min read
  • How to convert character to ASCII code using JavaScript ?
    The purpose of this article is to get the ASCII code of any character by using JavaScript charCodeAt() method. This method is used to return the number indicating the Unicode value of the character at the specified index. Syntax: string.charCodeAt(index); Example: Below code illustrates that they ca
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences