开发者

How do I get the unicode/hex representation of a symbol out of the HTML using JavaScript/jQuery?

开发者 https://www.devze.com 2023-03-18 23:31 出处:网络
Say I have an element like this... <math xmlns=\"http://www.w3.org/1998/Math/MathML\"> <mo class=\"symbol\">α</mo&g开发者_StackOverflow中文版t;

Say I have an element like this...

<math xmlns="http://www.w3.org/1998/Math/MathML">
  <mo class="symbol">α</mo&g开发者_StackOverflow中文版t;
</math>

Is there a way to get the unicode/hex value of alpha α, &#x03B1, using JavaScript/jQuery? Something like...

$('.symbol').text().unicode(); // I know unicode() doesn't exist
$('.symbol').text().hex(); // I know hex() doesn't exist

I need &#x03B1 instead of α and it seems like anytime I insert &#x03B1 into the DOM and try to retrieve it right away, it gets rendered and I can't get &#x03B1 back; I just get α.


Using mostly plain JavaScript, you should be able to do:

function entityForSymbolInContainer(selector) {
    var code = $(selector).text().charCodeAt(0);
    var codeHex = code.toString(16).toUpperCase();
    while (codeHex.length < 4) {
        codeHex = "0" + codeHex;
    }

    return "&#x" + codeHex + ";";
}

Here's an example: http://jsfiddle.net/btWur/


charCodeAt will get you the decimal value of the string:

"α".charCodeAt(0); //returns 945
0x03b1 === 945; //returns true

toString will then get the hex string

(945).toString(16); // returns "3b1"

(Confirmed to work in IE9 and Chrome)


If you would try to convert Unicode character out of BMP (basic multilingual plane) in ways above - you are up for a nasty surprise. Characters out of BMP are encoded as multiple UTF16 values for example:

"

0

精彩评论

暂无评论...
验证码 换一张
取 消