Javascript String convertHTML(str)

Description

Javascript String convertHTML(str)


/*/*  w  w w .  j  av a  2 s.c o  m*/

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.

Here are some helpful links:

RegExp
HTML Entities
String.prototype.replace()

*/

function convertHTML(str) {
  var exp = /[&<>"']/g;
  
  var htmlConvertTable = {
    '&':'&amp;',
    '<':'&lt;',
    '>':'&gt;',
    '\"':'&quot;',
    '\'':'&apos;'
  };
  
  return str.replace(exp,function(value) {
    return value.match(exp) ? htmlConvertTable[value] || value : value;
  });
}

console.log(convertHTML("Dolce & Gabbana"));



PreviousNext

Related