How can I escape HTML special chars in JavaScript?


HTML contains special characters such as ‘<,’ ‘>,’ ‘/,’ and many more such as single and double commas. These special characters are used for the HTML tag, such as ‘<’ is used to open the HTML tag. The ‘/’ and ‘>’ is used to close the HTML tag. This tutorial teaches us to escape HTML special characters in JavaScript.

Now, the question is that what if we want to use these characters inside the HTML content? If we use special characters normally in the HTML content, it considers it the opening or closing HTML tag and produces an unknown error.

For example, we need to render the below string to the browser.

<b> tutorialsPoint </b>

If we directly add the above string in the HTML, it considers <b> as the bold tag but we want to use it as a string.

To overcome the above problem, we must use Unicode for all the special characters. Here, we will replace all special characters with Unicode to escape HTML special chars and use them inside the HTML string.

There are different approaches to solve the above problem given below.

  • Using the createTextNode() Method
  • Using the textContent attribute
  • Using the replace() method

Using the createTextNode() method

In this approach, we will use the createTextNode() method from the HTML DOM. We just need to pass the string to the method as an argument, which returns the encoded string.

Syntax

Var converted_string = document.createTextNode(string);

Parameters

  • String − We can pass any HTML string as an argument to escape special characters and encode it.

Example 1

The below example demonstrate the use of createTextNode(string) method in JavaScript.

<!DOCTYPE html>
<html>
<body>
   <h2>Escape HTML special Chars in JavaScript.</h2>
   <h4> String After escaping the special characters: </h4>
   <p id = "contentDiv"> </p>
   <script type = "text/javascript">
      // function to escape special chars using createTextNode() method.
      function escapeSpecialChars() {
         let string_var = " <h1> tutorialsPoint </h1> ";
         let escapedString = document.createTextNode(string_var);
         contentDiv.appendChild(escapedString);
      }
      escapeSpecialChars();
   </script>
</body>
</html>

For the above example output, users can observe that we have created an encoded string using the createTextNode() method and inserted it into the HTML DOM. It renders special characters as it is without considering them as a tag element.

Using the textContent attribute

We can create an HTML element in JavaScript and add the HTML string. We can use the textContent property of the HTML Textarea element and insert the HTML string. After that, we can get encoded string with Unicode using the innerHTML property.

Syntax

let textAreaDiv = document.createElement( 'textarea' );
textAreaDiv.textContent = HTML_String;
let encoded_string = textAreaDiv.innerHTML;

Parameters

  • HTML_string − We can pass any HTML string which we want to encode as this parameter.

Example 2

Users can follow the below example to see the demonstration of the above approach.

<!DOCTYPE html>
<html >
<body>
   <h2>Escape HTML special Chars in javascript.</h2>
   <h4> String After escaping the special characters. </h4>
   <p id="resultDiv"> </p>
   <script type = "text/javascript">
      let textAreaDiv = document.createElement('textarea');
      var resultDiv = document.getElementById("resultDiv");
      textAreaDiv.textContent = "<div>Welcome to tutorialsPoint website.</div>";
      let encoded_string = textAreaDiv.innerHTML;
      resultDiv.innerHTML = encoded_string;
   </script>
</body>
</html>

Users can see in the below output that how we can encode string using the textContent property.

Using the Replace() method

In this approach, we will use the replace() method of JavaScript. We can use the replace() method to replace one character with another character. Here, We will replace all the special characters in the HTML string with their Unicode by using the replace() method.

Syntax

html_string.replace( old_char, new_char )

Parameters

  • Html_string − It is a string in which we need to escape special characters.

  • Old_char − It is a character in the string which needs to be replaced.

  • New_char − It is a character that we will add to the string at the position of the old character.

Example 3

The below example demonstrates how we can encode the HTML string by replacing the special characters using the replace() method.

<!DOCTYPE html>
<html>
<body>
   <h2>Escape HTML special chars</h2>
   <p> Result after escaping the special characters. </p>
   <p id="result"></p>
   <script>
      // function to escape special chars using replace() method.
      function escapeSpecialChars(str) {
         return str
         .replace(/&/g, "&")
         .replace(/</g, "<")
         .replace(/>/g, ">")
         .replace(/"/g, """)
         .replace(/'/g, "'");
      }
      let string = ` <div> hello user! <i>your welcome</i> here. </div>`;
      let escape = escapeSpecialChars(string);
      document.getElementById("result").innerHTML = escape;
   </script>
</body>
</html>

Users can see that we have successfully replaced all special characters using the replace method, and we can render the string as it is with special characters.

Conclusion

In this tutorial, we have learned three approaches to replacing the special characters in the HTML. Users can use any method according to their requirements.

Updated on: 14-Jul-2022

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements