如何使用 JavaScript/jQuery 从 HTML 中获取符号的 unicode/hex 表示形式?
假设我有一个像这样的元素...
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mo class="symbol">α</mo>
</math>
有没有办法使用 JavaScript/jQuery 获取 alpha α
、α
的 unicode/hex 值?就像...
$('.symbol').text().unicode(); // I know unicode() doesn't exist
$('.symbol').text().hex(); // I know hex() doesn't exist
我需要 α
而不是 α
,似乎任何时候我将 α
插入 DOM 并尝试立即检索它,它被渲染,我无法取回 α
;我刚得到α。
Say I have an element like this...
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mo class="symbol">α</mo>
</math>
Is there a way to get the unicode/hex value of alpha α
, α
, 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 α
instead of α
and it seems like anytime I insert α
into the DOM and try to retrieve it right away, it gets rendered and I can't get α
back; I just get α.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用大部分纯 JavaScript,您应该能够执行以下操作:
这是一个示例: http://jsfiddle.net/btWur/
Using mostly plain JavaScript, you should be able to do:
Here's an example: http://jsfiddle.net/btWur/
charCodeAt
将获取字符串的十进制值:toString
将获取十六进制字符串(已确认在 IE9 和 Chrome 中工作)
charCodeAt
will get you the decimal value of the string:toString
will then get the hex string(Confirmed to work in IE9 and Chrome)
如果您尝试将 Unicode 字符从 BMP(基本多语言平面) 转换出来以上述方式 - 你会遇到令人不快的惊喜。 BMP 之外的字符被编码为多个
UTF16
值,例如:"
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:"????".length
= 2 (one part for shackle one part for lock base :) )so
"????".charCodeAt(0)
will give you55357
which is only 'half' of number while"????".charCodeAt(1)
will give you56594
which is the other half.To get char codes for those values you might wanna use use following string extension function
you can also use it like this
to get html hex codes.
Hope this saves you some time.
例如,如果您需要将此十六进制代码转换为 unicode
e68891e4bda0e4bb96
返回 url 解码字符串
之前添加 %
函数 hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2){
}
for example in case you need to convert this hex code to unicode
e68891e4bda0e4bb96
return url decode string
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2){
}