template-helpers
Version:
Generic JavaScript helpers that can be used with any template engine. Handlebars, Lo-Dash, Underscore, or any engine that supports helper functions.
49 lines (43 loc) • 940 B
JavaScript
const string = require('./string');
/**
* Escape HTML characters in a string.
*
* ```js
* <%= escapeHtml("<span>foo</span>") %>
* //=> <span>foo</span>
* ```
*
* @param {String} `str` String of HTML with characters to escape.
* @return {String}
* @api public
*/
exports.escapeHtml = str => {
if (!string.isString(str)) return '';
return str.replace(/[/"'&<>]/g, ch => {
return ({
'"': '"',
'&': '&',
'/': '/',
'<': '<',
'>': '>',
'\'': '''
})[ch];
});
};
/**
* Strip HTML tags from a string, so that only the text nodes
* are preserved.
*
* ```js
* <%= sanitize("<span>foo</span>") %>
* //=> 'foo'
* ```
*
* @param {String} `str` The string of HTML to sanitize.
* @return {String}
* @api public
*/
exports.sanitize = str => {
return string.isString(str) ? str.replace(/(<([^>]+)>)/g, '').trim() : '';
};
;