このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
String.prototype.at()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2022年3月.
at() はString 値のメソッドで、整数値を受け取り、指定したオフセットに位置する 1 つの UTF-16 コード単位からなる新しい文字列を返します。このメソッドでは、正と負の整数を扱うことができます。負の整数の場合は、文字列の最後の文字から前へ数えます。
In this article
試してみましょう
const sentence = "The quick brown fox jumps over the lazy dog.";let index = 5;console.log(`An index of ${index} returns the character ${sentence.at(index)}`);// 予想される結果: "An index of 5 returns the character u"index = -4;console.log(`An index of ${index} returns the character ${sentence.at(index)}`);// 予想される結果: "An index of -4 returns the character d"構文
js
at(index)引数
index返す文字列のインデックス(位置)。負のインデックスを渡した場合、文字列の末尾からの相対位置指定に対応しています。つまり、負の数を使用した場合、文字列の末尾から数えて返す文字を見つけます。
返値
指定した位置にある単一の UTF-16 コード単位からなる文字列を返します。指定された位置が見つからない場合はundefined を返します。
例
>文字列の最後の文字を返す
次の例は、指定した文字列の中で最後に見つかった文字を返す関数です。
js
// 指定された文字列の最後の文字を返す関数function returnLast(str) { return str.at(-1);}let invoiceRef = "my-invoice01";console.log(returnLast(invoiceRef)); // '1'invoiceRef = "my-invoice02";console.log(returnLast(invoiceRef)); // '2'メソッドの比較
ここでは、文字列の最後から 2 番目の文字を選択する複数の方法を比較します。以下に示すどの方法も有効ですが、at() メソッドの簡潔さと読みやすさが際立っています。
js
const myString = "Every green bus drives fast.";// length プロパティと charAt() メソッドの使用const lengthWay = myString.charAt(myString.length - 2);console.log(lengthWay); // 't'// slice() メソッドの使用const sliceWay = myString.slice(-2, -1);console.log(sliceWay); // 't'// at() メソッドの使用const atWay = myString.at(-2);console.log(atWay); // 't'仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-string.prototype.at> |