Skip to content

Instantly share code, notes, and snippets.

@eday69
Last active June 15, 2018 17:55
Show Gist options
  • Save eday69/25bd91db022064256ca84d279c5b3bf0 to your computer and use it in GitHub Desktop.
Save eday69/25bd91db022064256ca84d279c5b3bf0 to your computer and use it in GitHub Desktop.
freeCodeCamp Intermediate Algorithm Scripting: Convert HTML Entities
// Convert the characters &, <, >, " (double quote), and ' (apostrophe),
// in a string to their corresponding HTML entities.
function convertHTML(str) {
// &colon;&rpar;
const convertHTML={ "&": "&amp;",
"<": "&lt;",
">": "&gt;",
"\"": "&quot;",
"'": "&apos;"}
return str.split("").map(letter => { return [
letter.match(/[&<>"']/) ? convertHTML[letter] : letter]
}).join("");
}
convertHTML("Dolce & Gabbana"); // Dolce &​amp; Gabbana
convertHTML("Hamburgers < Pizza < Tacos"); // Hamburgers &​lt; Pizza &​lt; Tacos
convertHTML("Sixty > twelve"); // Sixty &​gt; twelve
convertHTML('Stuff in "quotation marks"'); // Stuff in &​quot;quotation marks&​quot;
convertHTML("Schindler's List"); // Schindler&​apos;s List
convertHTML("<>"); // &​lt;&​gt;
convertHTML("abc"); // abc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment