Intermediate Algorithm Scripting: Convert HTML Entities

Intermediate Algorithm Scripting: Convert HTML Entities
0

#1

My way makes more sense to me than the ones in the Hints section, but I’d sure like some critique:

function convertHTML(str) {
  const arr = [["&","&amp;"],['>','&gt;'],['<','&lt;'],["'",'&apos;'],['"','&quot;']];
  for (let i=0; i < arr.length; i++)  {
    str = str.replace(new RegExp(arr[i][0],"g"),arr[i][1]);
  }
return str;
}

Edited to fix the bad copy/paste that made it fail the tests.


#2

The code you posted does not pass any of the tests. Also, unless you have something very specific to ask about a part of your code, please do not post full working solutions.

Critiques are not specific and they are very opinionated. Everybody thinks “their” solution is better than all the others. If anyone posts another solution on this thread, it will be closed and hidden, but typically that is the only kind of reply you will get.

A better question is, why do you think your solution makes more sense than the ones in the Hints section. I personally do not find your code very readable. All of your variable names should describe what they contain. Your variable a does not give the reader of your code any idea of what a is without studying the code. A more efficient solution would use a lookup object instead of an array for the replacement values.


#3

OK, thanks. Sorry for posting the wrong version.


#4

Thanks, this procedure helped me a lot:

function convertHTML(str) {
  // &colon;&rpar;
  const mapa = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&apos;"
  };

  console.log("Texto original:", str);
  for(let myKey in mapa) {
     str = str.replace(RegExp(myKey, 'g'), mapa[myKey]);
}
  return str;
}