Convert HTML Problems

Convert HTML Problems
0.0 0

#1

Tell us what’s happening:

Your code so far

function convertHTML(str) {
  // :)
  //var htmlents = ["&", ">", "<",""","'"];
  for(var i = 0; i < str.length; i++){
    if (str.indexOf('\'') >= 0){
      str = str.replace("'", "&apos;");
    }
    else if(str.indexOf('"') >= 0){
      str = str.replace('"', "&quot;");
    }
    else if(str.indexOf("&") >= 0){
     str = str.replace("&", "&amp;");
    }
    else if(str.indexOf('>') >= 0){
      str = str.replace('>', "&gt;");
    }
    else if(str.indexOf('<') >= 0){
      str = str.replace('<', "&lt;");
    }
  }
  return str;
}

convertHTML("Dolce & Gabbana");

Your browser information:

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

Link to the challenge:


#2

Hello everyone, for some reason, whenever I uncomment the & check, I get an infinite loop warning. My code works for every other check. Yes, I know I could have used a case statement.


#3

You are creating an infinite loop, because your for loop condition is based on str.length. Inside the for loop, the following else/if is causing the problem:

    else if(str.indexOf("&") >= 0){
     str = str.replace("&", "&amp;");
    }

On any given iteration of the for loop, you replace ‘&’ with ‘&’’ which increases the length of str and since you are adding another ‘&’ when you add the ‘&’, str gets larger and larger as you keep adding ‘&amp’ each time.

Suggestion: Get rid of the for loop all together and just use the replace statements you have, but you will need to perform them in a particular order to avoid creating extra & where they are not wanted.

Extra Hint: The basic replace method ONLY replaces the first instance found, so you will need to use a regular expression with the global modifier to replace all the instances.


#4

Thank you very much, this helped me solve the problem!