jquery .text() and unicode

后端 未结 4 943
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 15:03

I\'d like to display the \"Open Lock\" character in my HTML link text.

If I do it directly it shows up correctly with 🔒<

相关标签:
4条回答
  • 2021-02-01 15:35

    Following script should convert UTF32 hex values to UTF16 pairs

    function toUTF16Pair(hex) {
      hex = hex.replace(/[&#x;]/g,'');
        var x = parseInt(hex, 16);
        if (x >= 0x10000 && x <= 0x10FFFF) {
            var first = Math.floor((x - 0x10000) / 0x400) + 0xD800;
            var second = ((x - 0x10000) % 0x400) + 0xDC00;
            return {
                first: first.toString(16).toUpperCase(),
                second: second.toString(16).toUpperCase(),
              combined: '\\u'+first.toString(16).toUpperCase() + '\\u'+second.toString(16).toUpperCase()
            };
        } else {
            return {}
        }
    }
    <input type='text' id='in' />
    <input type='button' value='Click' onclick="document.getElementById('result').innerHTML = toUTF16Pair(document.getElementById('in').value).combined" />
    <p id='result'></p>

    0 讨论(0)
  • 2021-02-01 15:37

    editedIf it were a Unicode code point that could be represented in a single UTF-16 character, then ou could use JavaScript escape sequences in such situations:

    $('#foo').text('\uXXXX');
    

    However, because your character requires more bits, that doesn't work. It would probably be possible to construct the byte sequence that'd allow the character to be represented as UTF-16, but it'd be a pain. I'd go with .html().

    Note that not all fonts provide glyphs for "exotic" code points like that, and in my experience those that do provide incredibly ugly ones.

    0 讨论(0)
  • 2021-02-01 15:41

    You can put the character there directly, as a quoted string, e.g.

    $("#myID").text('                                                                    
    0 讨论(0)
  • 2021-02-01 15:48

    Javascript internally only supports UTF-16.

    Because this is an extended 32-bit UTF character (not in the "Basic Multilingual Plane") you need to insert the "UTF-16 surrogate pair", which is helpfully provided on the same page that you linked to:

    0xD83D 0xDD13
    

    i.e.

    $('#myId').text('\ud83d\udd13');
    

    More details can be found in RFC 4627, which is strictly speaking the format for JSON.

    0 讨论(0)
提交回复
热议问题