Convert html entities problem/

Why doesn’t my code for this convertHTML("<>"); particular case? All other cases pass successfully. This problem is from intermediate algorithm scripting


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


There are a few issues with your code in terms of best practices — it’s considerably more complicated than it needs to be.

However, having read your code, re-read it, run it, modified it, re-run it, and iterated that process 100 times, I have to say the actual bug was extremely difficult to find and results from a bizarrely terrible design decision in the implementation of JavaScript regexes. Explanation here:

Basically, if you remove the g flag, your code will run fine.

However, you can also clean it up a lot more. If you’re using regexes, try using multiple replaces sequentially on the whole string (but the order matters, especially in the case of &). Alternatively, you can convert the string to an array, in which case you don’t need regexes at all.

1 Like

Thank you so much for the solution.Yeah I know the code is way too long and needs to be refactored.I will implement your suggestions.Thanks again!