Saturday, July 25, 2020

Convert HTML Entities


Intermediate Algorithm Scripting: Convert HTML Entities

Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.

convertHTML("Dolce & Gabbana") should return "Dolce &amp; Gabbana".

convertHTML("Hamburgers < Pizza < Tacos") should return "Hamburgers &lt; Pizza &lt; Tacos". convertHTML("Sixty > twelve") should return "Sixty > twelve".

convertHTML('Stuff in "quotation marks"') should return "Stuff in "quotation marks"".

convertHTML("Schindler's List") should return "Schindler's List".

convertHTML("<>") should return "<>".

convertHTML("abc") should return "abc"

const HTML_ENTITIES = Object.freeze({
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&apos;'

function convertHTML(str) {
  return str.replace(/[&<>"']/g, result => HTML_ENTITIES[result]);

  'Dolce & Gabbana',
  'Hamburgers < Pizza < Tacos',
  'Sixty > twelve',
  'Stuff in "quotation marks"',
  "Schindler's List",
].forEach(param => console.log(convertHTML(param)));

Dolce &amp; Gabbana
Hamburgers &lt; Pizza &lt; Tacos
Sixty &gt; twelve
Stuff in &quot;quotation marks&quot;
Schindler&apos;s List

No comments:

Post a Comment