Convert HTML Entities

So I’m doing the Convert HTML Entities exercise and I typed up the following code:

function convertHTML(str) {
  const symbols = {
    "&": "&",
    "<": "&lt;",
    ">": "&gt;",
    "\"": "&quot;",
    "'": "&apos;"
  }
  for (const symbol in symbols) {
    if (str.indexOf(symbol) >= 0) {
      const newStr = str.replaceAll(symbol, symbols[symbol])
      return newStr
    }
  }
  return str;
}

I got all of the tests right except for this one:

convertHTML("<>") should return the string &lt;&gt; .

When I enter the string “<>” in the function, it replaces the first arrow but not the second. So I get "&lt;>" as a result. Can anyone tell me why that is?

@camperextraordinaire I tried using this code instead but it still doesn’t work:

function convertHTML(str) {
  const symbols = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    "\"": "&quot;",
    "'": "&apos;"
  }
  let newStr = str
  for (const symbol in symbols) {
    if (str.indexOf(symbol) >= 0) {
      newStr = str.replaceAll(symbol, symbols[symbol])
    }
  }
   return newStr;
}

I moved the return keyword outside of the loop and declared the newStr variable outside of the loop as well. I had to make it equal to str at first so the string would stay the same if no symbols are present. I tried it again but instead I get the second arrow replaced instead of the first (<&gt;).

I just want to keep trying my own solutions before I use one of the hints.

This is the problem. You are still referencing the original string each time when you should be referencing newStr based on the rest of your code.

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