Javascript function htmlentities and html_entity_decode


Function html_entity_decode

Method 1:

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

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

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

Related Post

No comments yet.

Leave a Reply