I’m working on the Convert HTML Entities challenge. It’s still incomplete as I’m not taking all test cases into account (especially the ‘abc’ one). However, I’m experiencing a weird error with the ‘<>’ test case. It’s supposed to return '<>', but what I get is '<>'.
This is my code so far:
function convertHTML(str) {
// :)
let charEntities = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'\'': '''
};
let newStr = '';
for (let i = 0; i < str.length; i++) {
for (var j in charEntities) {
if (str[i] == j) {
newStr = str.split(str[i]).join(charEntities[j]);
}
}
}
return newStr;
Testing it on both VS Code and Repl.it yields the same result as mentioned above. The editor over at fCC doesn’t even return any replacements, just the same ‘<>’.
I tried several variations using both symbols, but the problem seems to arise as soon as both symbols are present in the same string.
About the logic issues, yes, they’re expected because, as I said in my original post, it’s still incomplete – I need to cover for the ‘abc’ case, for example.
I have manually typed the values in both VS Code and Repl.it and get the same results. What really draws my attention is how the error happens whenever ‘<’ and ‘>’ appear in the same string.
Actually, found - considering you always start from str to get the value of newStr this will work only for one html entity to convert, because the next one will start again from str deleting what you did previously
This works because you have the same entity repeated, the other situation in which it doesn’t work is when you have different entities in the same string
Instead of creating a new string every time over I splitted it into an array first, checked against the object entities and reassigned the array items that fulfilled the condition, joining the array back into a string at the end:
function convertHTML(str) {
// :)
let charEntities = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'\'': '''
};
let newStr = '';
let strArr = str.split('');
for (let i = 0; i < strArr.length; i++) {
for (var j in charEntities) {
if (strArr[i] == j) {
strArr[i] = charEntities[j];
}
}
}
newStr = strArr.join('');
return newStr;
}
These are basically the same edge cases that got me rethinking my approach in the first place. Again, these two cases pass everywhere else. Could it be a bug in fCC? Should I report it? Is there a workaround?
Again, thanks in advance!
Scrape that! It was, again, a hidden character problem here: '<': '<',