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 & Gabbana".
convertHTML("Hamburgers < Pizza < Tacos") should return "Hamburgers < Pizza < 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({
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": '''
});
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 & Gabbana Hamburgers < Pizza < Tacos Sixty > twelve Stuff in "quotation marks" Schindler's List <> abc
No comments:
Post a Comment