0

I am working on this assignment on free code camp, and for some reason, which I can't seem to figure out, I am not getting the correct output. My debug logs seem to occur as expected, but it seems as though I'm missing something. I have used string.replace() before with an anonymous function, and it worked fine. In this case, I don't seem to be actually replacing my matches on the string as expected, and I imagine it has something to do with using the regex for matches.

I can't figure out how to make this go. Any help would be appreciated.

Code:

function convertHTML(str) {
  var re = new RegExp('[$\"\'\<\>&]', 'g');
  str.replace(re, function (match) {
    console.log("match");
    console.log(match);
    switch (match) {
      case "&":
        return "&amp;";
      case "$":
        return "&dollar;";
      case '"':
        return "&quot;";
      case "'":
        return "&apos;";
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
    }
    console.log("oops");
  });
  console.log(str);
  return str;
}

convertHTML("Dolce & Gabbana");
convertHTML("Hamburgers < Pizza < Tacos");
convertHTML("Sixty > twelve");
convertHTML('Stuff in "quotation marks"');
convertHTML("Shindler's List");
convertHTML("<>");
NotAnAmbiTurner
  • 2,553
  • 2
  • 21
  • 44
  • 1
    You are forgetting to assign, `replace` is not *in-place* so change to: `str = str.replace(re, function (match) {` – Alex K. Feb 09 '17 at 18:51

1 Answers1

1

String.prototype.replace() does not change the String object it is called on. It simply returns a new string.

...
// to change/overwrite the initial string
str = str.replace(re, function (match) {
...
});
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105