Convert HTML Entities-problem in a for Loop

Tell us what’s happening:
hello everybody, im trying to figure out what is the problem there as i use this switch -case in a for Loop and it works for all the tests except this one ‘<>’. It seems it makes the first replacement right the second also right but it can not keep both changes till the end. It is like for every new change it uses again the initial str and not the newStr. Is there any ideas how i can fix this?

Your code so far

function convertHTML(str) {
  // &colon;&rpar;
   var newStr=str;
  var spaceRemover = str.split(' ').join('');

   for(i=0; i<str.length; i++){
     
  switch (true) {
     
    case str[i].includes('&'):
       newStr=spaceRemover.replace(/&/g, ' &amp; ');
      break;
    case str[i].includes('<'):
      newStr=spaceRemover.replace(/</g, ' &lt; ');
      break;
      
     case str[i].includes('>'):
      newStr=spaceRemover.replace(/>/g, ' &gt; ');
      break;
     case str[i].includes('"'):
      newStr=newStr.replace(/"/g, '&quot;');
      break;
      case str[i].includes("'"):
      newStr=newStr.replace(/'/g, '&apos;');
      break;
   
  }

 }
console.log(newStr);
 return newStr;
}
convertHTML("<>");

Your browser information:

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

Link to the challenge:
https://www.freecodecamp.org/challenges/convert-html-entities

i finaly found the solution i use arrays instead of strings with the same logic!

Hello! And why use loop at all? The method .replace () itself searches in what place the necessary element is located and changes it. I did this:

function convertHTML(str) {
  str = str.replace(/&/g, '&amp;');
  str = str.replace(/</g, '&lt;');
  str = str.replace(/>/g, '&gt;');
  str = str.replace(/"/g, '&quot;');
  str = str.replace(/'/g, '&apos;');
    
  return str;
}

Can anyone know the best solution? Share, please :slight_smile:

Thank you! Very laconic and elegant! Only I did not understand how this part of the code works:
find => conversions [find]
Explain, please, if it is not difficult.

Oh, so that’s clear. Thank you :slight_smile:

i am used this code

function convertHTML(str) {
var arr=[];
arr=str.split(’’);
function replacer(char){
switch(char){
case ‘<’:
return ‘<’;
case ‘>’:
return ‘>’;
case ‘&’:
return ‘&’;
case ‘"’:
return ‘"’;
case “’”:
return ‘’’;
default:
return char;
}
}
for (var i=0;i<arr.length;i++){
arr[i]=replacer(arr[i]);
}
str=arr.join(’’);
// :slight_smile:
return str;
}

convertHTML(“Dolce & Gabbana”);