Convert HTML Entities

function convertHTML(str) {
  let convertHTMLEntities= {
    "&": "&",
    "<": "&lt;",
    ">": "&gt;",
    "\\"": "&quot;",
    "'": "&apos;"
  }
  //str.split("").map
  return str.replace(/(\\&)|(\\<)|(\\>)|(\\")|(\\')/g, (match)=> {
    return convertHTMLEntities[match]//match 相当于$&,即匹配的子串
  })
}
convertHTML("Dolce & Gabbana");

测试数据:

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.

//别人家的孩子
str.replace(/([&<>\\"'])/g, match => htmlEntities[match]);

return str
    .split("")
    .map(entity => htmlEntities[entity] || entity)
    .join("");