Created
February 1, 2018 22:51
-
-
Save bozdoz/d204966b16fc029b090ec667c7a280cc to your computer and use it in GitHub Desktop.
HTML from Array of strings
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
/* | |
* utility variables for escaping HTML | |
*/ | |
// escapeMap, borrowed from underscore.js | |
var escapeMap = { | |
'&': '&', | |
'<': '<', | |
'>': '>', | |
'"': '"', | |
"'": ''', | |
'`': '`' | |
}; | |
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><b>Text</b></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