→
その String 中の指定位置にある単一の UTF-16 コード ユニットからなる文字列を返します。
str | ¶String、文字列。 |
---|---|
index | 0 から str.length -1 までの間の整数です。index が整数に変換できない場合や index が指定されなかった場合、既定値は 0 となり、str の最初の文字が返されます。 |
文字(String)。指定された index の位置にある文字(厳密に 1 つの UTF-16 コード ポイント)を表す文字列です。index の位置が文字列の範囲を外れていた場合は、charAt() は空文字列を返します。
文字列の中の文字は、左から右に向けてインデックス付けされています。最初の文字の添字は 0 であり、最後の文字の添字は ― stringName という名前の文字列であれば ― stringName.length -1 です。提供した index がこの範囲を外れていた場合、JavaScript は空文字列を返します。
index が charAt() に提供されなかった場合の既定値は 0 です。
次の例は、"Brave new world" という文字列の中の様々な位置の文字を表示します。
//コンソールにて var anyString = 'Brave new world'; console.log("The character at index 0 is '" + anyString.charAt() + "'"); // index が提供されなかった場合は、既定値として 0 が使われる console.log("The character at index 0 is '" + anyString.charAt(0) + "'"); console.log("The character at index 1 is '" + anyString.charAt(1) + "'"); console.log("The character at index 2 is '" + anyString.charAt(2) + "'"); console.log("The character at index 3 is '" + anyString.charAt(3) + "'"); console.log("The character at index 4 is '" + anyString.charAt(4) + "'"); console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
これらの行は以下のように表示されます。
The character at index 0 is 'B'
The character at index 0 is 'B'
The character at index 1 is 'r'
The character at index 2 is 'a'
The character at index 3 is 'v'
The character at index 4 is 'e'
The character at index 999 is ''
S='Brave new world'; D=S.charAt(10); //="w"