jQuery: escaping HTML entities

In this post I'm going to mimic with jQuery the core PHP functions used to encode HTML special characters. We start by creating a new jQuery global function to escape HTML entities such as <, > and &.

(function($) {

    $.htmlSpecialChars = function(value) {
    if(typeof value !== 'string') {
        throw new Error('htmlSpecialChars() works with strings.');
   var converted = value.replace(/<+/g, '<').
                  replace(/>+/g, '>').
      replace(/"+/g, '"').
      replace(/&+/g, '&'); 
      return converted;


This function makes use of the replace() method to encode all entities by replacing them with regular expressions, using the g modifier. A basic usage is the following:

$(document).ready(function() {

    $('#test').submit(function(e) {
     var text = $(this).find('textarea').val();
  var converted = $.htmlSpecialChars(text);
  $('#result')[0].innerHTML = converted;


You can see this example here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.