htmlspecialchars() for JavaScript

Creating markup with JavaScript for fun and profit is easy due to innerHTML. However, it would be nice to be able to escape output that is not trusted or known. Most references online point to encodeURI or encodeURIComponent, which will kind-of work; however those functions are intended for URI escaping, which has different rules.

So, here’s a quick solution that works pretty much like the similarly-named PHP function, htmlspecialchars:

function htmlspecialchars(str) {

    if (str === undefined) return "";
 
    return str.replace(/[<>"&]/g, function(match){
        return (match == "<") ? "&lt;" :
               (match == ">") ? "&gt;" :
               (match == '"') ? "&quot;" :
               (match == "&") ? "&amp;" : "";
    });
}

What’s missing? The “quote_style” parameter which allows deciding what will happen with single quotes (‘). If your markup is sane and under control, there should be no need for it — if it isn’t, it’s not hard to change the above function.

Leave a Reply