Saturday, July 25, 2020

Convert HTML Entities

From: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/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",
  '<>',
  'abc'
].forEach(param => console.log(convertHTML(param)));


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

No comments:

Post a Comment