Question about Convert HTML Entities

So here’s my code for that assignment so far:

function convertHTML(str) {
  // :)
  var re = /(\&|<|>|\"|\')/g;
  var newstr = "";
  re = /\&/g;
  newstr = str.replace(re, "&amp;");
  re = /</g;
  newstr = str.replace(re, "&lt;");
  re = />/g;
  newstr = str.replace(re, "&gt;");
  return newstr;

convertHTML("Dolce < Gabbana");

The issue is the < and > entries aren’t working as intended. I tried putting \ before the < and it gives me a warning and the output doesn’t change, in both cases it just returns the exact same text. I tried looking it up on Google and on this forum and I can’t find the answer. Any suggestions?

The problem is that you are overwriting newstr each time. So in line before the return, you overwrite it again so nothing that was done with newstr before that will matter. In other words, your logic is basically working and thos chars are being replaced, but unless it is that last thing to be replaced you’ll never see it.

Instead of using newstr, why not write it back to str.

str = str.replace(re, "&amp;");

So, we just replace those chars and save the new string into str. You do that each time for each char that then return that.

That worked, thanks. I added some more code for str.replace using " and ’ but for the sake of not showing spoilers I’ll leave the code alone.