Skip to content

Instantly share code, notes, and snippets.

@mingyun
Created March 7, 2014 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mingyun/9408976 to your computer and use it in GitHub Desktop.
Save mingyun/9408976 to your computer and use it in GitHub Desktop.
输入中文文字,按“转化”,即可将其转化为unicode字符
var mode="zhuan";
function encode(obj,btn){
if(mode=="zhuan"){
obj.value=obj.value.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"\\u$2")});
btn.value="还原";
mode="huan";
}else{
obj.value=unescape(obj.value.replace(/\\u/g,'%u').replace(/;/g,''));
btn.value="转化";
mode="zhuan";
}
}
function convert2Unicode(char) {
return "\\u" + char.charCodeAt(0).toString(16);
}
function toUnicode(theString) {
var unicodeString = '';
for (var i = 0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return unicodeString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment