HTML entities are defined in HTML, not JavaScript. To use the entity names in JavaScript, you thus need to make a JavaScript interpreter parse data as HTML. A simple way to achieve this is to assign data to the innerHTML
property of an element. So starting from an entity name, construct an HTML entity reference by prefixing it with &
and suffixing it with ;
, assign it, then process the (parsed) value, a character. You can convert the character to its Unicode number using charCodeAt()
and then write the number in hexadecimal using toString()
with 16 as the argument:
var ent = 'cent'; // just an example; "ent" contains the entity name
var elem = document.createElement('span');
elem.innerHTML = '&' + ent + ';';
var ref = '\\' + elem.innerHTML.charCodeAt(0).toString(16);
// now ref contains a string like \a2 (you may need to add zeros or append a
// space if you write this into CSS
I don’t see what the point is here, though. You could use just the characters themselves in HTML, JavaScript, and CSS, provided that you deal with character encoding issues properly, as you should anyway.