How can I escape HTML special chars in JavaScript?

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

Now, the question is what if we want to use these characters inside the HTML content? If we use special characters normally in HTML content, it considers them as opening or closing HTML tags 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 HTML, it considers <b> as the bold tag but we want to use it as a string.

To overcome this problem, we must use HTML entities for all special characters. Here, we will replace all special characters with their corresponding HTML entities to escape HTML special chars and use them inside HTML strings.

There are different approaches to solve the above problem:

  • 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

The below example demonstrates 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>
<h1> tutorialsPoint </h1>

In the above example, we have created an encoded string using the createTextNode() method and inserted it into the HTML DOM. It renders special characters as text without considering them as HTML elements.

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 the encoded string with HTML entities 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

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>
<div>Welcome to tutorialsPoint website.</div>

In the above output, you can see how we can encode strings using the textContent property. The textarea element automatically escapes HTML entities.

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 special characters in the HTML string with their HTML entities 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

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, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#39;");
      }
      let string = `<div> hello user! <i>you're welcome</i> here. </div>`;
      let escape = escapeSpecialChars(string);
      document.getElementById("result").innerHTML = escape;
   </script>
</body>
</html>
<div> hello user! <i>you're welcome</i> here. </div>

You can see that we have successfully replaced all special characters using the replace method, and we can render the string as text with visible special characters.

Comparison

Method Complexity Browser Support Best For
createTextNode() Low All browsers Simple text insertion
textContent Low All modern browsers Getting escaped HTML strings
replace() Medium All browsers Custom escaping logic

Conclusion

In this tutorial, we learned three approaches to escape HTML special characters in JavaScript. The createTextNode() method is simplest for DOM insertion, while the replace() method offers the most control over escaping logic.

Updated on: 2026-03-15T23:18:59+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements