Convert HTML Entities

function convertHTML(str) {

  let newStr = str.split(""); 

  for (let i = 0; i < newStr.length; i++) {
    if (str.replace("&", "&amp;"));
    if (str.replace("<", "&lt;"));
    if (str.replace(">", "&gt;"));
    if (str.replace('"', "&quot;"));
    if (str.replace("'", "&apos;"));
  newStr = newStr.join(""); 
  return newStr;

console.log(convertHTML("Dolce & Gabbana"));

Confused about how to go about replacing characters with new ones. Any help/guidance without giving away any answers would be greatly appreciated. Thanks!

Some hints:

  • What is the data type of newStr? Is it a string? Or does it start as something else?
  • You’re using str.replace(), which replaces values in str, but returning newStr.
  • Spoilering this one: What if you didn’t make an array and loop? What if you just used str.replace()?
1 Like
function convertHTML(str) {

const chars = {

return str.replace(/([&<>""'])/g, m => chars[m]);

console.log(convertHTML("Dolce & Gabbana"));

Thank you!! Figured it out

Nice work! That’s a solid approach - I usually see campers chain .replace() calls for each symbol, but passing a callback function to replace is a much cleaner (and more advanced) approach. :grin:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.