Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

String.fromCharCode()

概要

Unicode の値の指定のシーケンスを使用することによって生成された文字列を返します。

構文

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

引数

num1, ..., num N
Unicode の値の数のシーケンス。

説明

このメソッドは String オブジェクトではなく文字列を返します。

fromCharCodeString の静的メソッドなので、自分で生成した String オブジェクトのメソッドではなく、常に、String.fromCharCode() を使用するようにしてください。

Example: Using fromCharCode

The following example returns the string "ABC".

String.fromCharCode(65,66,67)

Getting it to work with higher values

Although most common Unicode values can be represented with one 16-bit number (as expected early on during JavaScript standardization) and fromCharCode() can be used to return a single character for the most common values (i.e., UCS-2 values which are the subset of UTF-16 with the most common characters), in order to deal with ALL legal Unicode values (up to 21 bits), fromCharCode() alone is inadequate. Since the higher code point characters use two (lower value) "surrogate" numbers to form a single character, String.fromCodePoint() (part of the ES6 draft, see below for a shim) can be used to return such a pair and thus adequately represent these higher valued characters.

Be aware, therefore, that the following method to grab the full code point even for higher value code points, may be returning a value which is rendered as a single character, but which has a string count of two (though usually the count will be one).

// String.fromCharCode() alone cannot get the character at such a high code point
// The following, on the other hand, can return a 4-byte character as well as the 
//   usual 2-byte ones (i.e., it can return a single character which actually has 
//   a string length of 2 instead of 1!)
alert(String.fromCodePoint(0x2F804)); // or 194564 in decimal

/*!
* From: (c) 2012 Steven Levithan <https://slevithan.com/>
* MIT License
*/
if (!String.fromCodePoint) {
    /*!
    * ES6 Unicode Shims 0.1
    * (c) 2012 Steven Levithan <https://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("");
    }
}

関連情報

ドキュメントのタグと貢献者

 このページの貢献者: teoli, ethertank, Mgjbot, Potappo
 最終更新者: teoli,