Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities.
& - & < - < > - > " - " ' - '
function convertHTML(str) { function swapChar(charToSwap){ // that swaps characters to HTML entities switch(charToSwap){ case "&": return "&"; break;//from w ww.j ava 2 s . c o m case "<": return "<"; break; case ">": return ">"; break; case '"': return """; break; case "'": return "'"; break; default: return "ERROR"; break; } } str = str.replace(/[&<>"']/g, function(match){ // find any of given character, then call function to swap chars return swapChar(match); }); return str; } console.log(convertHTML("Dolce & Gabbana"));;// should return Dolce &?amp; Gabbana. console.log(convertHTML("Hamburgers < Pizza < Tacos"));;// should return Hamburgers &?lt; Pizza &?lt; Tacos. console.log(convertHTML('Stuff in "quotation marks"'));;// should return Stuff in &?quot;quotation marks&?quot;.