Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to decode hex code of html entities to text in javascript? [duplicate]

I am facing a difficulty in converting hex values of string characters to normal test values for example hex value of ' to sting is ' i.e an apostrophe.

Another values of hex characters can be found on this link : http://character-code.com/.

Can someone please tell me if a javascript method exists to do so or should I be using some external javascript library plug-in for this purpose?

I have already tried using URIencode and URIencodecomponent but no luck

like image 693
neeraj Avatar asked Sep 14 '25 21:09

neeraj


2 Answers

You can use the host–provided parser to insert the entity in an element, then get back the textContent (or innerText where supported instead):

var el = document.createElement('span');
el.innerHTML = ''';

console.log('' is a ' +  (el.textContent || el.innerText));  // ' is a '

Of course that won't work for entities the browser doesn't support.

Edit

To turn the above into a function:

var entityToText = (function() {

  // Create a single span to parse the entity
  var span = document.createElement('span');

  // Choose textContent or innerText depending on support
  var theText = typeof span.textContent == 'string'? 'textContent' : 'innerText';

  // Return the actual function
  return function(entity) {
    span.innerHTML = entity;
    return span[theText];
  }
}());
like image 162
RobG Avatar answered Sep 17 '25 10:09

RobG


You can use String.fromCharCode - but you will first need to convert the hex value (base 16) to an integer (base 10). Here's how you would do that:

    var encoded = "'";
    var REG_HEX = /&#x([a-fA-F0-9]+);/g;

    var decoded = encoded.replace(REG_HEX, function(match, group1){
        var num = parseInt(group1, 16); //=> 39
        return String.fromCharCode(num); //=> '
    });

    console.log(decoded); //=> "'"

To convert the decimal back to hex, you can do this:

    decoded.toString(16); //=> 27
like image 40
Ryan Wheale Avatar answered Sep 17 '25 11:09

Ryan Wheale