I’m a bit confused with this challenge. My code is not working when an argument does not have a symbol in it, such as convertHTML("abc")
function convertHTML(str) {
var symbols = ["&", "<", ">", '"', "'"];
var html = ["&", "<", ">", """, "'"];
var newStr = "";
for (var i=0; i<symbols.length; i++) {
if (str.indexOf(symbols[i]) !== -1) {
newStr = str.replace(symbols[i], html[i]);
if (i == (symbols.length-1) && newStr.length<1) {
newStr = str; //abc argument not returning anything
}
}
}
return newStr;
}
convertHTML("abc");
They way I figured this would work is that the 2nd if statement would kick in when the loop gets to the end of the symbol array, and newStr is still empty, meaning that it did not detect any symbols. It would then just return the original string. How come it’s not working as expected?
function convertHTML(str) {
var symbols = ["&", "<", ">", '"', "'"];
var html = ["&", "<", ">", """, "'"];
var newStr = "";
for (var i=0; i<symbols.length; i++) { //CONVERT PHRASE WITH SYMBOL
if (str.indexOf(symbols[i]) !== -1) {
newStr = str.replace(new RegExp(symbols[i], 'g'), html[i]);
}
else if (i == (symbols.length-1) && newStr.length<1) {
newStr = str; //RETURNS STR IF NO SYMBOL PRESENT
}
}
return newStr;
}
convertHTML("<>");
My code is being passed for everything except convertHTML("<>"); Currently it returns <> I’ve think I’ve determined this is because the way I’ve written my code it does not handle the replacement of two types of symbols. However I don’t understand the current output. In my array of symbols less < comes first, so I’d expect the output to be <> Testing shows that < on it’s own returns < but if I change the argument to convertHTML("><") the output is >< Whats going on here?!
It’s amazing how writing out your problem in the forum can help you troubleshoot! Once I submitted I realized that what was happening was that my loop would continue to run after something would replace. And as per the original code it would update the string with only the last found symbol in the array. I changed it so that var newStr = str & newStr = newStr.replace(new RegExp(symbols[i], 'g'), html[i]);