Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Created March 23, 2018 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickihastings/ec2576f55efa2a9ac20d357a61ca5102 to your computer and use it in GitHub Desktop.
Save nickihastings/ec2576f55efa2a9ac20d357a61ca5102 to your computer and use it in GitHub Desktop.
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