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("'", "'");
}
else if(str.indexOf('"') >= 0){
str = str.replace('"', """);
}
else if(str.indexOf("&") >= 0){
str = str.replace("&", "&");
}
else if(str.indexOf('>') >= 0){
str = str.replace('>', ">");
}
else if(str.indexOf('<') >= 0){
str = str.replace('<', "<");
}
}
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:
https://www.freecodecamp.org/challenges/convert-html-entities
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.
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("&", "&");
}
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 ‘&’ 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.
1 Like
Thank you very much, this helped me solve the problem!