Skip to content

Instantly share code, notes, and snippets.

@NKid
Last active August 19, 2020 05:05
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 NKid/b708fe48ff2f869b5015 to your computer and use it in GitHub Desktop.
Save NKid/b708fe48ff2f869b5015 to your computer and use it in GitHub Desktop.
[字串轉換為unicode編碼] Convert a String to Unicode
console.log('好'.charCodeAt()); //22909
console.log('好'.charCodeAt().toString(16)); //597d
console.log(String.fromCharCode(22909)); //好
console.log(String.fromCharCode(0x597d)); //好
console.log('\u597d'); //好
console.log('\u{597d}'); //好
//prototype 擴充類別定義
//方法1 (Regex)
String.prototype.toUnicode = function() {
return this.replace(/./g, function(char) {
var v = char.charCodeAt(0).toString(16);
var pad = "0000";
return (pad.substring(0, pad.length - v.length) + v).toUpperCase();
});
};
console.log('狂'.toUnicode()); //72C2
//方法2 (while)
String.prototype.toUnicode = function () {
return this.replace(/./g, function (char) {
var v = String.charCodeAt(char).toString(16);
if (v.length != 4) {
do {
v = '0' + v;
} while (v.length < 4)
}
return v;
});
};
console.log('狂'.toUnicode()); //72C2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment