Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, convert unicode string to Javascript escape?

Tags:

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:

"\u306f\u3044\u3044\u308d"

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

like image 925
Jamus Avatar asked Jan 09 '14 07:01

Jamus


2 Answers

"み".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();       //"\u307f\u3069\u308a\u3044\u308d" "Mi Do Ri I Ro".toUnicode();  //"\u004d\u0069\u0020\u0044\u006f\u0020\u0052\u0069\u0020\u0049\u0020\u0052\u006f" "Green".toUniCode();          //"\u0047\u0072\u0065\u0065\u006e" 

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

More on: .charCodeAt

like image 112
Derek 朕會功夫 Avatar answered Sep 22 '22 08:09

Derek 朕會功夫


Above answer is reasonable. A slight space and performance optimization:

function escapeUnicode(str) {     return str.replace(/[^\0-~]/g, function(ch) {         return "\\u" + ("000" + ch.charCodeAt().toString(16)).slice(-4);     }); } 
like image 34
Adam Leggett Avatar answered Sep 22 '22 08:09

Adam Leggett