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.'); return; } var converted = value.replace(/<+/g, '<'). replace(/>+/g, '>'). replace(/"+/g, '"'). replace(/&+/g, '&'); return converted; }; })(jQuery);
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; e.preventDefault(); }); });
You can see this example here.