4

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

Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
neeraj
  • 101
  • 1
  • 2
  • 5

3 Answers3

8

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];
  }
}());
RobG
  • 142,382
  • 31
  • 172
  • 209
8

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
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
  • +1 The only code based answer in the web. Very nice thank you. I used your approach to write a function which is in my answer below. – Bamdad Nov 22 '21 at 09:47
3

Just use this function derived from Ryan Wheale's solution to convert any numerical hex Html string to a friendly string:

function hexHtmlToString(str) {
    var REG_HEX = /&#x([a-fA-F0-9]+);/g;
    return str.replace(REG_HEX, function(match, grp){
        var num = parseInt(grp, 16);
        return String.fromCharCode(num);
    });
}

Usage:

var str = 'سلام';
console.log(hexHtmlToString(str)); //results: سلام
Bamdad
  • 726
  • 1
  • 11
  • 28