Skip to content

Instantly share code, notes, and snippets.

@datchley
Last active August 29, 2015 14:07
Show Gist options
  • Save datchley/97587b4ebac34f641fef to your computer and use it in GitHub Desktop.
Save datchley/97587b4ebac34f641fef to your computer and use it in GitHub Desktop.
Javascript string escape utilities
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.returnExports = factory();
}
}(this, function () {
// Add entities to replace in HTML here
var entityMap = {
"&": "&",
"<": "&lt;",
">": "&gt;",
'"': '&quot;',
"'": '&#39;',
"/": '&#x2F;'
},
// build matcher from entityMap
reEntityMatch = new RegExp('[' + escapeRegExp(Object.keys(entityMap).join('')) + ']','g');
// Escape a string to be used in a regular expression
function escapeRegExp(string) {
return string.replace(/[\/\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
// Allow "abc".escapeRegExp()
String.prototype.escapeRegExp = function() {
return escapeRegExp(this.toString());
};
// Escape HTML entities in a string for output
function escapeHtml(string) {
return string.replace(reEntityMatch, function (s) {
return entityMap[s];
});
}
// Allow "abc".escapeHtml()
String.prototype.escapeHtml = function() {
return escapeHtml(this);
};
return {
'escapeRegExp': escapeRegExp,
'escapeHtml': escapeHtml
};
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment