The Single Function Module

A function, all by itself:

module.exports = function(string) {
  return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
};

This is the escapeHTML() function from Backbone.js, which is hidden behind a closure. Thankfully it’s now in the latest version of Underscore.js, which is depended upon by Backbone. If an old version of underscore was being used and escapeHTML() was the one missing utility function that a developer needed, putting it in a module by itself would be one way of supplying it.

Side note: Backbone and Underscore escape the exact six characters specified in Rule #1 of the Open Source Web Application Security Project (OWASP)’s XSS (Cross Site Scripting) Prevention Cheat Sheet.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.