Created
March 23, 2018 18:48
-
-
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.
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
function convertHTML(str) { | |
// :) | |
//create an object to store the html conversions | |
var htmlEntities = { | |
'&' : '&', | |
'<' : '<', | |
'>' : '>', | |
'"' : '"', | |
"'" : ''' | |
}; | |
//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