This is the challenge:
Convert the characters & , < , > , " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.
I am having trouble debugging this code. As far as I can tell I’ve wrote everything correctly but it doesnt work for the two specific instances in the logs at the bottom.
The hamburgers pizza taco one is apparently correct when I log it, but doesnt satisfy the requirements.
The <> returns <> and I can’t figure out why.
Thanks (this is my first forum post, I’d gladly take suggestions on how best to format these questions in the future)
You don’t need to use replace that many times. You’re basically running through the string each time you do it. Plus, it’s harder to visually see, vs creating a Map.
So if you’re serious about becoming better at programming I highly recommend learning how to use MDN’s site.
If you scroll down and click syntax you’ll see this:
var newStr = str.replace(regexp|substr, newSubstr|function)
If you scroll further down within that section it describes what those variables are.
Notice how the last parameter there says “function”.
Which means you can do: 'kzollove & FCC'.replace(/&/, (char) => { console.log(char); });
The bold is regexp and function in documentation.
whenever javascript finds a match it passes that value to the function.
So with the example above,. characters kzollove[space] do nothing… but when it gets to & that value becomes char and now char is used in your function.
Sorry for the late response, but I really appreciate the big reply you left me. Good advice on MDN. I have been accessing it a little bit but it always strikes me as daunting and I usually navigate to easier to decipher sources. I will put in the time in the future.
Thanks for the advice on the alg. Perfect amount of a hint to get me to the finish line. I knew from the start I needed a way to selectively replace, but your demonstration of the replace method helped me get there finally.
**spoiler ** my final algorithm for anyone interested
function convertHTML(str) {
let x =
{'&': '&',
'<': '<',
'>': '>',
'\"': '"',
'\'': '''
}
return str.replace(/[&<>\"\']/g, char => { return x[char] })
}