Convert HTML Entities: Code converts back to the symbols

Hello! I’m trying to solve this challenge in “Intermediate Algorithms” and I’m running into a problem. The problem is asking to replace HTML entity symbols with their correct representation (i.e. & becomes &). Essentially, when I’m doing a switch-case to find the correct substitute, the console output converts back to the exact symbol I’m trying to convert. Code is below - it’s incomplete, as I’m simply trying to debug.

function convertHTML(str) {
  // :)
  var regex = /&|<|>|'|"/
  var replacer = ""
  var checker = str.match(regex).toString()

  console.log(regex.test(str))

  if (regex.test(str)) 
  {
    switch (checker)
    {
        case "&":
        replacer = '&amp;'
        break;
        
        case "<":
        replacer = "&lt;"
        break;

        case ">":
        replacer = "&gt;"
        break;

        case "'":
        replacer = "&apos;"
        break;

        case '"':
        replacer = "&quot;"
        break;
    }
  }

  console.log(replacer)

  return str;
}

convertHTML("Dolce & Gabbana");

As I said in the introduction, console.log(replacer) gives out “&” instead of “& amp;”. In fact, I just found out it happens in this very text box, so I had to insert a space in there. Is there any way I can do the correct substitution? An explanation as to why this is happening would be priceless; I find string operations extremely confusing. Thank you!

As both this and the FreeCodeCamp editor are web pages you may not see the html entity even if it used instead of the symbol as they are converted directly when shown
For example if I quote your code you see this:

But let’s put it under backticks…

[quote="loxagossnake, post:1, topic:271032"]
convertHTML("Dolce &amp; Gabbana");
[/quote]

The &amp; appear


Possibilities: use browser console, or a tool like http://pythontutor.com/javascript.html

1 Like

Thank you! It didn’t dawn on me to just press the Run button, and, voila, it works…for some of the tests.

Back to the drawing board it is!

Maybe check the function calls of those tests you are missing with one of the tools I mentioned above