Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.
function convertHTML(str) {
// &colon;&rpar;
//create an object to store the html conversions
var htmlEntities = {
'&' : '&amp;',
'<' : '&lt;',
'>' : '&gt;',
'"' : '&quot;',
"'" : '&apos;'
//function takes the match and finds the related conversion from the object
function convertHTML(match){
return htmlEntities[match];
//regex = match any one of the characters in the square brackets
return str.replace(/[&<>"']/g, convertHTML);
convertHTML("Dolce & Gabbana");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment