escape html string in jquery

How to Escape HTML Strings With jQuery

jQuery is a powerful JavaScript library that allows you to easily manipulate DOM elements and web pages. While rendering strings and text in JavaScript processing, it is important to escape HTML characters in them, if any. Otherwise, if you create a DOM element out of such a string, it may allow malicious users to inject JavaScript/HTML into your website. Since such strings are typically received during form submission, stored in database and rendered on client side when page is loaded, it allows anyone to easily submit HTML/JavaScript code via user forms or other methods. In this article, we will learn how to escape HTML string with jQuery. It is advisable to use this method as a validation during form submissions before storing them in your back end database, instead of using them during HTML rendering.


How to Escape HTML Strings With jQuery

There are several ways to escape HTML strings with jQuery. We will learn a couple of simple ones.

1. Using Character Map

Here is a simple JavaScript function to escape HTML strings.

var charMap = {
  '&': '&',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return charMap[s];
  });
}

In the above function, we create a character map of commonly use HTML characters, mapped to their Unicode equivalents. We create a function escaptHtml where we replace all occurrences of characters present in character map, in the string, with their Unicode equivalents. We use replace() JS function for this purpose.


2. Using text() function

You can also convert HTML characters in string to their Unicode equivalent by calling text() function on them. Here is an example. Let us say you have the following div.

<div class="myDiv">text</div>

Let us say you want to add the following text to this div.

var someHtml = "<script>alert('hi!');</script>";

You can do so with the following command.

$("div.myDiv").text(someHtml);

After escaping html string, your div will look like.

<div class="myDiv">&lt;script&gt;alert('hi!');&lt;/script&gt;</div>

In this article, we have learnt how to escape HTML strings with jQuery.

Also read:

How to Check if Element is Visible or Hidden in jQuery
Set NGINX to Catch All Unhandled Virtual Hosts
How to Do Case Insensitive Rewrite in NGINX
How to Forward Request to Another Port in NGINX
How to Check if Key Exists in Python Dictionary

Leave a Reply

Your email address will not be published. Required fields are marked *