2

I am able to dynamically produce an Unicode character and insert it into a <div> by using sequences like &#x00f0;, but now I want to retrieve this input as an escape sequence, not the character itself.

Please see 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()); 
});​

In other words, when I click "get mytext's source", I want to fill in the textarea with &#x00f0; and not ð. Is this possible? If so, how?

2 Answers 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) + ';';
      }));
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it using charCodeAt() to obtain decimal charcode, then convert it to hex with toString(16) , as follows:

   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);

See working demo

1 Comment

the Number's toString method with radix, learning something new everyday. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.