How to convert special characters to HTML in Javascript?


We can use replace() method to convert special characters to HTML in JavaScript. This method can also be applied with a map. There are many other methods that can be used for this task. We will discuss these methods in detail in this article. We will start our discussion with the need to convert special characters to HTML then, we will talk about the methods of converting the special characters. Firstly, let’s talk about some concepts of characters, and then we will come up with our next topics.

Need to Convert Special Characters to HTML

We have seen our developers writing thousands of lines of code to achieve a particular task. Now, let’s suppose we need to use less than(<) or greater than(>) sign in our web-page or say mobile application that uses HTML as a scripting language. Then, it would become a problem as less than(<) and greater than(>) signs have special meaning to the scripting language HTML.

These signs are generally used to initialize a tag in HTML. Similarly, using a special character, either < or > within an attribute value might cause the attribute to be misinterpreted. Hence, to overcome this problem, we have special codes for every special character that exist while using HTML.To insert special characters in HTML, start with an ampersand (&), then a pound symbol (#), then the code number, and finish with a semicolon (;). For example, the (copyright) symbol can be represented by using ©.

Methods to Convert Special Characters to HTML

There are several ways to convert special characters to HTML. Some of the most common ways to do so are listed below.

Using the String.prototype.replace() Method

The String.prototype.replace() method in JavaScript is used to replace the special character with another value in the string.

String.prototype.replace() takes two parameters, first one is the value to be replaced, and the second parameter is the value to replace it within the string.

This method returns a new string with all the search values replaced with the desired value in the string. However, the String.prototype.replace() method does not change the value of the existing string. Let’s see an example.

Example

<html>
<body>
   <p id="print"></p>
   <script>
      var string = "This is a <string>";
      string = string.replace(/</g, "<");
      document.getElementById("print").innerHTML = string;
   </script>
</body>
</html>

Using the String.prototype.replace() with a Map

The String.prototype.replace() method can also be used with a Map in JavaScript. Here also String.prototype.replace() takes two parameters, first one is the regular expression pattern to be replaced, and the second parameter is the matched substrings.

Example

Let’ see an example of using map with string.prototype.replace() −

<html>
<body>
   <p id="print"></p>
   <script>
      const specialCharsMap = new Map([
         ["<", "<"],
         [">", ">"],
         ["&", "&"],
      ]);
      function replaceSpecialChars(string) {
         for (const [key, value] of specialCharsMap) {
            string = string.replace(new RegExp(key, "g"), value);
         }
         return string;
      }
      document.getElementById("print").innerHTML =
      replaceSpecialChars("This is a <string>");
   </script>
</body>
</html>

Using the encodeURIComponent() Function

We can also use encodeURIComponent() Function in javascript to replace the special character with another value in the string. We generally use this function to encode a Uniform Resource Identifier (URI) component.It replaces specific characters in a string with escaped counterparts to ensure that the string can be safely used in a URI.

Now, to use this function we simply pass the string (str) as a parameter in the function. This method also returns a new string with all the search values replaced with the desired value in the string. Like the String.prototype.replace() method this function also does not change the value of the existing string. Let’s see an example.

Example

<html>
<body>
   <p id="print"></p>
   <script>
      var str = "Hello, < world > !";
      var newStr = encodeURIComponent(str);
      document.getElementById("print").innerHTML = newStr;
   </script>
</body>
</html>

While using this function one should keep in mind that it only works for a few special characters. To work with some other special characters, multiple methods or additional logic must be used to handle them.

Using the escape() Function

The escape() function like encodeURIcomponent() function is used to encode a string so that it does not cause any problem with the URL of the website. To use this function we simply pass the string (str) as a parameter in the function. This method also returns a new string with all the search values replaced with the desired value in the string.

Example

Here is the example of escape() function −

<html> 
<body>
   <p id="print"></p>
   <script>
      var str = "Hello, <world>!";
      var newStr = escape(str);
      document.getElementById("print").innerHTML = newStr;
   </script>
</body>
</html>

Conclusion

In this blog, we firstly started with the introduction of special characters, the need to convert them, and various methods that can be used to do so. Some of the discussed methods here are Using the String.prototype.replace(), Using the String.prototype.replace() with a Map, Using the encodeURIComponent() Function, and the escape() function. Some other methods that can be used are innerHTML, replace, document.createElement, etc.

Updated on: 21-Feb-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements