Javascript function htmlentities and html_entity_decode


Function html_entity_decode

Method 2:

var html_entity_decode = (function() {
  var cache = {},
    character,
    e = document.createElement('div');

  return function(html) {
    return html.replace(/([&][^&; ]+[;])/g, function(entity) {
      character = cache[entity];
      if (!character) {
        e.innerHTML = entity;
        if (e.childNodes[0])
          character = cache[entity] = e.childNodes[0].nodeValue;
        else
          character = '';
      }
      return character;
    });
  };
})();

Try it yourself

Method 2

var html_entity_decode2 = function(input) {
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

Try it yourself

Method 3:

var html_entity_decode = function(str) {
  return str.replace(/&#(x[0-9a-fA-F]+|\d+);/g, function(match, dec) {
    return String.fromCharCode(dec.substr(0, 1) == 'x' ? parseInt(dec.substr(1), 16) : dec);
  })
};

Example:

alert(html_entity_decode('高级程序设计'))

Try it yourself

Function htmlentities

var htmlentities = function(str) {
  var buf = '';
  for (var i = 0; i < str.length; i++) {
    buf += '&#' + str.charCodeAt(i) + ';';
  }
  return buf;
};

Try it yourself

Leave a Reply