ostduq
Last Updated: February 25, 2016
·
27.15K
· gohan

Escape HTML with Javascript

Source

That's a pretty standard way of doing it, my version used a <div> though:

return $('<div/>').text(t).html();

This isn't technically 100% safe though as Mike Samuel notes but it is probably pretty safe in practice.

The current Prototype.js does this:

function escapeHTML() {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

But it used to use the "put text in a div and extract the HTML" trick.

There's also _.escape in Underscore, that does it like this:

// List of HTML entities for escaping.
var htmlEscapes = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#x27;',
  '/': '&#x2F;'
};

// Regex containing the keys listed immediately above.
var htmlEscaper = /[&<>"'\/]/g;

// Escape a string for HTML interpolation.
_.escape = function(string) {
  return ('' + string).replace(htmlEscaper, function(match) {
    return htmlEscapes[match];
  });
};

That's pretty much the same approach as Prototype's. Most of the JavaScript I do lately has Underscore available so I tend to use _.escape these days.

2 Responses
Add your response

13259

Ben Vinegar's You are probably misusing DOM text methods convinced me not to use DOM fragments to escape HTML. Below mixin was inspired by Ben's post and the Mustache.js implementation for sanitizing HTML from user input

/** Mixin to extend the String type with a method to escape unsafe characters
 *  for use in HTML.  Uses OWASP guidelines for safe strings in HTML.
 * 
 *  Credit: http://benv.ca/2012/10/4/you-are-probably-misusing-DOM-text-methods/
 *          https://github.com/janl/mustache.js/blob/16ffa430a111dc293cd9ed899ecf9da3729f58bd/mustache.js#L62
 *
 *  Maintained by stevejansen_github@icloud.com
 *
 *  @license http://opensource.org/licenses/MIT
 *
 *  @version 1.0
 *
 *  @mixin
 */
(function(){
  "use strict";

  function escapeHtml() {
    return this.replace(/[&<>"'\/]/g, function (s) {
      var entityMap = {
          "&": "&amp;",
          "<": "&lt;",
          ">": "&gt;",
          '"': '&quot;',
          "'": '&#39;',
          "/": '&#x2F;'
        };

      return entityMap[s];
    });
  }

  if (typeof(String.prototype.escapeHtml) !== 'function') {
    String.prototype.escapeHtml = escapeHtml;
  }
})();
over 1 year ago ·
13292

@steve-jansen Underscore already did same as your snippets :)

over 1 year ago ·