-
-
Save NKid/b708fe48ff2f869b5015 to your computer and use it in GitHub Desktop.
[字串轉換為unicode編碼] Convert a String to Unicode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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