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
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.
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];
}
}());
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With