2

我能够动态生成一个 Unicode 字符,并<div>通过使用类似的序列将其插入到 a 中&#x00f0;,但现在我想将此输入检索为转义序列,而不是字符本身。

请参阅此 JSFiddle 示例

<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”时,我想在textarea中填入&#x00f0;而不是ð。这可能吗?如果是这样,怎么做?

4

2 回答 2

2
$("#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) + ';';
      }));
于 2012-10-20T20:52:17.150 回答
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);

查看工作演示

于 2012-10-20T20:46:10.147 回答