lunedì 29 novembre 2010

Replacing HTML entities with the appropriate characters in Javascript

I was looking for a good Javascript example to replace HTML entities with the appropriate characters and, after a long search, I found out this thread on stackoverflow. The function below, proposed by the user Tomalak, works like a charm for me:

var replaceHtmlEntites = (function() {
    var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
    var translate = {
        "nbsp": " ", // Space
        "amp" : "&", // Char &
        "quot": "\"", // Char "
        "lt"  : "<", // Char <
        "gt"  : ">" // Char >
    };
    return function(s) {
        return (s.replace(translate_re, function(match, 
                                                 entity) { 
            return translate[entity];
        }) );
    }
})();
callable as
var strIn ="This string has special chars &amp; and &nbsp;";
var strOut = replaceHtmlEntites(strIn);


Best regards.