Skip to content

Instantly share code, notes, and snippets.

@bozdoz
Created February 1, 2018 22:51
Show Gist options
  • Save bozdoz/d204966b16fc029b090ec667c7a280cc to your computer and use it in GitHub Desktop.
Save bozdoz/d204966b16fc029b090ec667c7a280cc to your computer and use it in GitHub Desktop.
HTML from Array of strings
/*
* utility variables for escaping HTML
*/
// escapeMap, borrowed from underscore.js
var escapeMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;'
};
var escapeRegex = new RegExp(Object.keys(escapeMap).join('|'), 'g');
/**
* Maps left-hand special characters with
* HTML encoded strings
*
* @param String match
* @return String
*/
function escapeFun (match) {
return escapeMap[match];
}
/**
* Creates a string of HTML from an array of strings
* optionally nested with more arrays of strings.
* Also makes childless tags self-closing
*
* ex:
* ['br'] => '<br/>'
* ['h1', 'Text'] => '<h1>Text</h1>'
* ['a', ['b', 'More'], ' Text'] =>
* '<a><b>More</b> Text</a>'
* ['p', '<b>Text</b>'] => '<p>&lt;b&gt;Text&lt;/b&gt;</p>'
*
* @param Array _arr
* @return String HTML
*/
function SimpleHTML (_arr) {
var arr = _arr || [],
tagName = arr[0],
len = arr.length,
output = '';
// no input
if (!tagName) {
// could throw new Error
return '';
}
output = '<' + tagName;
// single input
if (len === 1) {
return output + '/>';
}
output += '>';
// for loop starts at second input (i = 1)
for (var i = 1; i < len; i++) {
var item = arr[i];
if (typeof(item) === 'string') {
// append strings as plaintext
output += item.replace(escapeRegex, escapeFun);
} else if (item instanceof Array) {
// recursively call this function for arrays
output += SimpleHTML(item);
}
}
// add the closing tag
output += '</' + tagName + '>';
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment