Last active
August 29, 2015 14:07
-
-
Save datchley/97587b4ebac34f641fef to your computer and use it in GitHub Desktop.
Javascript string escape utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 = { | |
"&": "&", | |
"<": "<", | |
">": ">", | |
'"': '"', | |
"'": ''', | |
"/": '/' | |
}, | |
// 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