Skip to content

Instantly share code, notes, and snippets.

@dan-f
Last active March 11, 2016 20:33
Show Gist options
  • Save dan-f/1d3436d048454abf5fa8 to your computer and use it in GitHub Desktop.
Save dan-f/1d3436d048454abf5fa8 to your computer and use it in GitHub Desktop.
Utilities for escaping and interpolating HTML strings in JS
// Requires underscore.js
var HTML,
Html;
HTML = function HTML (string) {
this.string = string;
};
HTML.prototype.toString = function toString() {
return this.string.toString();
}
Html = function Html(string, options) {
if (!_.isString(string) && !(string instanceof HTML)) {
throw new Error('Expected a string');
}
if (!_.isObject(options) && typeof options !== 'undefined') {
throw new Error('If provided, options must be an object');
}
if (_.isUndefined(options)) {
return new HTML(string);
} else {
return new HTML(string.replace(/{\w+}/g, function (parameter) {
var substitution = options[parameter.slice(1,-1)];
if (substitution instanceof HTML) {
return substitution;
} else {
return _.escape(substitution);
}
}));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment