"Convert HTML Entities" algo works on all but one test case

"Convert HTML Entities" algo works on all but one test case
0.0 0

#1

Hi,

My solution passes all but one test case and that confuses me. The difference with other cases is that, in this case there is nothing in the string other than the chars that are being replaced but I don’t see why that should make a difference. Can anyone explain? The result I get for the test case is “undefined” It should be “<&gt:”.

My code is as follows:

function convertHTML(str) {
  // &colon;&rpar;
  return str.replace(/[&<>"']+/g, htmlEncode);
 
  function htmlEncode(match){
    switch(match){
      case "&":
        return "&amp;";
        break;
      case "<":
        return "&lt;";
        break;
      case ">":
        return "&gt;";
        break;
      case '"':
        return "&quot;";
        break;
      case "'":
        return "&apos;";
        break;
    }
  }
}

convertHTML("<>");

ps I realise the breaks are superfluous - just good habits to include them :slight_smile:


#2

Actually - I figured it out. The “+” in my regex meant that when two entities are next to each other they count as a single match and obviously the string “<>” does not appear in the switch statement and so they are replaced with undefined (empty return from the inline function in the replace call. Simply removing “+” from the regex solves the problem. Cheers!