Convert HTML Entities

Convert HTML Entities
0

#1

Dear Forum,

I can’t understand where am I wrong. Cant get the correct return. The code is below:

function convertHTML(str) {
  // :)
 var arr = ['&', '<', '>', '"', "'"];
  var str1='';
 for (var i=0; i<arr.length; i++){
 
    switch (arr[i]){
      case '&':str.replace(/&/,'&amp');
               break;
      case '<':str.replace(/</,'&lt');
               break; 
      case '>':str.replace(/>/,'&gt');
               break;  
      case '"':str.replace(/"/,'&quot');
               break;
      case "'":str.replace(/'/,'&apos');
               break;  
    }
 
 } 
  return str;
}

convertHTML("Dolce & Gabbana");

#2

There are three problems I can see.

Firstly - consider this I just wrote in the inspector console:

>var str = 'hello'
undefined
>str.replace(/h/,'j')
"jello"
>str
"hello"

str.replace performs a change to the string on the fly, but it doesn’t change permanently. When you return str at the end, you get your unchanged string.

Secondly, what you are replacing it with is not exactly correct…look carefully at what you are supposed to replace the html entities with.

Finally, some of the tests require you to make multiple replacements within the string - so look into ‘greedy’ regex.


#3

Thanks @JacksonBates for your advise.