(Convert HTML Entities) tests not passing even though i get the right results [SOLVED]

I tried all the different tests and got the right results, but they’re still not passing, except for the last one

My code so far


function convertHTML(str) {
  let result=str+''
  const regex=/[&<>"']/
  for(let i=0;i<result.length;i++){
    if(regex.test(result.charAt(i))){
      switch(result.charAt(i)){
        case '&':
        result=result.replace("&","&amp;")
        i+=5
        break;

        case '<': 
        result=result.replace("<","&​lt;")
        i+=4
        break;

        case '>':
        result=result.replace(">","&​gt;")
        i+=4
        break;

        case '"':
        result=result.replace('"',"&​quot;")
        i+=6
        break;

        case "'":
        result=result.replace("'","&​apos;")
        i+=6
        break;
      }
    }
  }
  console.log(result) 
  console.log(result==="Stuff in &​quot;quotation marks&​quot;") 
  return result
} 
 
convertHTML('Stuff in "quotation marks"');    

My browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities/

Part of your problem is you need to manually type out the replacement values, because it seems you might have copied/pasted from a source which had some hidden characters which are causing the tests not to recognize the final string returned.

The other problem is in the test case of convertHTML("<>"), your code returns '&lt;>' instead of '&lt;&gt;

The reason is because i starts at 0 in the for loop and then after the first iteration, the case code block for case ‘<’ increments i by 4 to make i = 4. Then before your second iteration starts, your for loop’s 3rd expression (i++) increments i by 1 and so the for loop checks the condition of 5 < result.length. Since result.length at this point is equal to 5, and since 5 < 5 evaluates to false, the for loop stops.

2 Likes

I will confirm @camperextraordinaire’s suggestion. Had hidden chars in my solution too.

Thank you for finding the problem, Indeed manually typing the replacement values did fix the problem.

And for the “<>” test i just went ahead and reduced all the incremented values by 1 since the last character is “;” it won’t change anything.

The test passed.