【问题标题】:How do I retrieve Unicode escape sequence with jQuery or plain JavaScript?如何使用 jQuery 或纯 JavaScript 检索 Unicode 转义序列?
【发布时间】:2012-10-20 20:20:35
【问题描述】:

我能够动态生成一个 Unicode 字符并将其插入到 <div> 中,方法是使用像 ð 这样的序列,但现在我想将此输入作为转义序列检索,而不是字符本身。

请看this JSFiddle example:

<button id="insertDh">insert funny d to mytext</button>
<div id="mytext"><i>mytext: please click button above</i></div>
<hr>
<textarea id="theSource"></textarea>
<button id="getSource">get mytext's source</button>

$("#insertDh").click(function() {
    $("#mytext").html("&#x00f0;");
});

$("#getSource").click(function() {
   $("#theSource").val($("#mytext").html()); 
});​

也就是说,当我点击“get mytext's source”时,我想用&amp;#x00f0;而不是ð来填写textarea。这可能吗?如果有,怎么做?

【问题讨论】:

    标签: javascript jquery unicode


    【解决方案1】:
    $("#theSource").val(
        $("#mytext").html()
        // Replace non-ascii code-points with HTML entities.
        .replace(
          /[\ud800-\udbff][\udc00-\udfff]|[^\x00-\xff]/g,
          function (nonAscii) {
            var codepoint;
            if (nonAscii.length === 1) {  // A single basic-plane codepoint.
              codepoint = nonAscii.charCodeAt(0);
            } else {  // A surrogate pair representing a unicode scalar value.
              codepoint = 0x10000 + (
                ((nonAscii.charCodeAt(0) & 0x3ff) << 10)
                 | (nonAscii.charCodeAt(0) & 0x3ff));
            }
            return '&#x' + codepoint.toString(16) + ';';
          }));
    

    【讨论】:

      【解决方案2】:

      您可以使用charCodeAt()获取十进制字符码,然后使用toString(16)将其转换为十六进制,如下:

         temp = $("#mytext").html().charCodeAt(0).toString(16);
         while (temp.length < 4) {
            temp = '0'+temp; //complete hex number with zeros to obtain four digits
         }
         temp = '&#x' + temp + ';';
         $("#theSource").val(temp);
      

      查看工作demo

      【讨论】:

      • NumbertoString 方法与基数,每天学习新东西。 +1
      猜你喜欢
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 2011-05-29
      • 2021-01-30
      • 2018-05-26
      • 1970-01-01
      相关资源
      最近更新 更多