Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

jquery - Javascript, convert unicode string to Javascript escape?

I have a variable that contains a string consisting of Japanese characters, for instance;

"みどりいろ"

How would I go about converting this to its Javascript escape form?

The result I am after for this example specifically is:

"u306fu3044u3044u308d"

I'd prefer a jquery approach if there's a variation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
"み".charCodeAt(0).toString(16);

This will give you the unicode (in Hex). You can run it through a loop:

String.prototype.toUnicode = function(){
    var result = "";
    for(var i = 0; i < this.length; i++){
        // Assumption: all characters are < 0xffff
        result += "\u" + ("000" + this[i].charCodeAt(0).toString(16)).substr(-4);
    }
    return result;
};

"みどりいろ".toUnicode();       //"u307fu3069u308au3044u308d"
"Mi Do Ri I Ro".toUnicode();  //"u004du0069u0020u0044u006fu0020u0052u0069u0020u0049u0020u0052u006f"
"Green".toUniCode();          //"u0047u0072u0065u0065u006e"

Demo: http://jsfiddle.net/DerekL/X7MCy/

More on: .charCodeAt


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...