Convert HTML Entities attempt solve with if else

Convert HTML Entities attempt solve with if else
0.0 0

#1

Tell us what’s happening:

Can someone please help me out as to why this code isn’t working it only works for strings with & but none of the other symbols. Greatly appreciate it any help

Your code so far

function convertHTML(str) {
  // :)

var symbolPattern = /[&,<,>]/g; 
var htmlString = "";
  
if(str.match(symbolPattern) == "&") {
  htmlString = str.replace("&", "&amp;");
} else if(str.match(symbolPattern) == "<") {
  htmlString = str.replace("<", "&lt;");
} else if (str.match(symbolPattern) == ">") {
 htmlString = str.replace(">", "&ngt;");
}
  return htmlString;
}


convertHTML("Dolce & Gabbana");

Your browser information:

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

Link to the challenge:


#2

Hi @sunshadow,

A couple of things I notice:

  1. Your regex doesn’t need the commas- Click the link to see it explained in detail.

  2. Your regex uses the global flag, and str.match() should output an array, as MDN explains, so if there is more than one element to that array, your equality tests will fail.

    • Javascript is WEIRD about equality. Check out this JSFiddle to see why it works for “Dolce & Gabbana”, but won’t work for “<div>”
  3. Your if/else statements make it so that if a string has both an ampersand and an angle bracket, it will stop executing after the first condition is met.