- 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 the 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;
}
##Another Solution
function convert(str) {
//map of key:value pairs
var html = {
"&":"&",
"<":"<",
">":">",
"\"":""",
"\'":"'"
};
str = str.replace(/&|<|>|"|'/gi, function(matched){
return html[matched];
});
return str;
}
##Another Solution
function convert(str) {
//Chaining of replace method with different arguments
str = str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''');
return str;
}
- Read comments in code.
If you found this page useful, you can give thanks by copying and pasting this on the main chat: thanks @Rafase282 @jhalls for your help with Bonfire: Convert HTML Entities
NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)