Bonfire Convert HTML Entities - GJSmith3rd/FreeCodeCamp-BootCamp GitHub Wiki
Gilbert Joseph Smith III
Github | FreeCodeCamp | CodePen | LinkedIn | Blog/Site | E-Mail
- Difficulty: 2/5
Convert the characters "&", "<", ">", '"' (double quote), and "'" (apostrophe), in a string to their corresponding HTML entities.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
function convert(str) {
// :)
return str;
}
convert('Dolce & Gabbana');- You have to create a program that will convert HTML entities from string to their corresponding HTML entities. There are only a few so you can use different methods.
- You can use regular Expressions however I didn't in this case.
- You will benefit form a chart with all the html entities so you know which ones are the right ones to put.
- You should separate and string and work with each character to convert the right ones and then join everything back up.
Solution ahead!
function convert(str) {
// Split by character to avoid problems.
var temp = str.split('');
// Since we are only checking for a few HTML elements I used a switch
for (var i = 0; i < temp.length; i++) {
switch (temp[i]) {
case '<':
temp[i] = '<';
break;
case '&':
temp[i] = '&';
break;
case '>':
temp[i] = '>';
break;
case '"':
temp[i] = '"';
break;
case "'":
temp[i] = ''';
break;
}
}
temp = temp.join('');
return temp;
}- Read comments in code.