Skip to content

Instantly share code, notes, and snippets.

@cweider
Last active December 11, 2015 17:48
Show Gist options
  • Save cweider/4636723 to your computer and use it in GitHub Desktop.
Save cweider/4636723 to your computer and use it in GitHub Desktop.
var HTML_ENTITY_MAP = {
'&': '&'
, '<': '&lt;'
, '>': '&gt;'
, '"': '&quot;'
, "'": '&#x27;'
, '/': '&#x2F;'
};
// OSWASP Guidlines: &, <, >, ", ' plus forward slash.
var HTML_CHARACTERS_EXPRESSION = /[&<>"'\/]/g;
function _escapeHTML(text) {
return text.replace(HTML_CHARACTERS_EXPRESSION, function (c) {
return HTML_ENTITY_MAP[c] || c;
});
}
// OSWASP Guidlines: escape all non alphanumeric characters in ASCII space.
var HTML_ATTRIBUTE_CHARACTERS_EXPRESSION =
/[\x00-\x2F\x39-\x40\x5B-\x60\x7B-\xFF]/g;
function _escapeHTMLFanatic(text) {
return text.replace(HTML_ATTRIBUTE_CHARACTERS_EXPRESSION, function (s) {
if (HTML_ENTITY_MAP[s]) {
return HTML_ENTITY_MAP[s];
} else {
return "&#x" + ('00' + s.charCodeAt(0).toString(16)).slice(-2) + ";";
}
});
}
function escapeHTML(text) {
var value;
if (typeof (HTMLString.escapeHTML) == 'function') {
value = SafeString.escapeHTML(text);
} else if (HTMLString.escapeHTML === 'fanatic') {
value = _escapeHTMLFanatic(text);
} else if (HTMLString.escapeHTML === 'strict') {
value = _escapeHTML(text);
} else {
value = _escapeHTML(text);
}
}
function HTMLString(object) {
this._text = object.toString();
this._html = null;
}
function wrap(object) {
var instance;
if (object instanceOf HTMLString) {
instance = object;
} else if (object && object.toHTML && object.toText) {
instance = object;
} else {
instance = new this(object);
}
}
HTMLString.wrap = wrap;
HTMLString.prototype = new function () {
function toString() {
return this.toHTML();
}
function toHTML() {
if (!this._html) {
this._html = HTMLString.escapeHTML(this._text);
}
return this._html;
},
function toText() {
return this._text;
}
function valueOf() {
return this.toHTML().valueOf();
}
this.toHTML = toHTML;
this.toText = toText;
this.toString = toString;
this.valueOf = valueOf;
}();
if (typeof "exports" === 'object') {
exports.HTMLString = HTMLString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment