String.fromCharCode() 將Unicode 轉成字元

javascript中的string.fromCharCode()方法可以將多個Unicode轉成字串。

注意一點,這是個靜態函數,不能藉由物件實體來呼叫。

只能以String.fromCharCode()的方式使用。

String.fromCharCode()的語法:

String.fromCharCode(num1, ..., numN)

String.fromCharCode()的範例:

<script type="text/javascript">
 document.writeln(String.fromCharCode(65,66,67,68));
</script>

String.fromCharCode()的範例輸出:

ABCD

String.fromCharCode()方法可以處理任何一個16bit的Unicode,譬如說UTF-16 的子集UCS-2 ,

在大部分的的情況下,fromCharCode()方法是足夠使用的。若是要處理大於16字元的unicode,

可以參考Mozilla Developer Network的網頁提供的辦法:

alert(String.fromCodePoint(0x2F804));// or 194564 in decimal
/*!* From: (c) 2012 Steven Levithan <http://slevithan.com/>
* MIT License
*/
if(!String.fromCodePoint) {
/*!   
* ES6 Unicode Shims 0.1   
* (c) 2012 Steven Levithan <http://slevithan.com/>   
* MIT License   
*/
 String.fromCodePoint = function fromCodePoint() {
 var chars = [], point, offset, units, i;
 for( i = 0; i < arguments.length; ++i) {
    point = arguments[i];
    offset = point - 0x10000;
    units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point];
    chars.push(String.fromCharCode.apply(null, units));
 }
 return chars.join("");
}
}

關於字串物件的其他方法可以參考部落格內的另一篇文章:字串(String)物件

 
 

  按個讚!~支持本站!~

FB推薦載入中  

你可能會有興趣的文章: