Skip to content

Instantly share code, notes, and snippets.

@passy
Forked from remy/gist:375100
Created April 22, 2010 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save passy/375113 to your computer and use it in GitHub Desktop.
Save passy/375113 to your computer and use it in GitHub Desktop.
/**
* == Can it be done? ==
*
* I want to get from keyIdentifier to actual character, eg from U+0023
* to \u0023 - which if dropped in a string is the # character:
* http://jsconsole.com/?%22\u0023%22
*
* The problem is the starting point, and I know I can do it using an
* eval, but eval is evil, right? So how can I do it?
*
* Can you solve this?
* - @rem
*/
/**
* Taken from http://rishida.net/tools/conversion/.
*/
function hex2char ( hex ) {
// converts a single hex number to a character
// note that no checking is performed to ensure that this is just a hex number, eg. no spaces etc
// hex: string, the hex codepoint to be converted
var result = '';
var n = parseInt(hex, 16);
if (n <= 0xFFFF) {
result += String.fromCharCode(n);
} else if (n <= 0x10FFFF) {
n -= 0x10000
result += String.fromCharCode(0xD800 | (n >> 10)) + String.fromCharCode(0xDC00 | (n & 0x3FF));
} else {
result += 'hex2Char error: Code point out of range: '+dec2hex(n);
}
return result;
}
function convertUnicode2Char (str) {
// converts a string containing U+... escapes to a string of characters
// str: string, the input
// first convert the 6 digit escapes to characters
str = str.replace(/[Uu]\+10([A-Fa-f0-9]{4})/g, function(matchstr, parens) {
return hex2char('10'+parens);
});
// next convert up to 5 digit escapes to characters
str = str.replace(/[Uu]\+([A-Fa-f0-9]{1,5})/g, function(matchstr, parens) {
return hex2char(parens);
});
return str;
}
var code = "U+0023";
convertUnicode2Char(code); // #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment