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 ã³ã¼ãåä½ãããªãæ°ããæååãè¿ãã¾ãããã®ã¡ã½ããã§ã¯ãæ£ã¨è² ã®æ´æ°ãæ±ããã¨ãã§ãã¾ããè² ã®æ´æ°ã®å ´åã¯ãæååã®æå¾ã®æåããåã¸æ°ãã¾ãã
試ãã¦ã¿ã¾ããã
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"
æ§æ
at(index)
弿°
index-
è¿ãæååã®ã¤ã³ããã¯ã¹ï¼ä½ç½®ï¼ãè² ã®ã¤ã³ããã¯ã¹ã渡ããå ´åãæååã®æ«å°¾ããã®ç¸å¯¾ä½ç½®æå®ã«å¯¾å¿ãã¦ãã¾ããã¤ã¾ããè² ã®æ°ã使ç¨ããå ´åãæååã®æ«å°¾ããæ°ãã¦è¿ãæåãè¦ã¤ãã¾ãã
è¿å¤
æå®ããä½ç½®ã«ããåä¸ã® UTF-16 ã³ã¼ãåä½ãããªãæååãè¿ãã¾ããæå®ãããä½ç½®ãè¦ã¤ãããªãå ´å㯠undefined ãè¿ãã¾ãã
ä¾
>æååã®æå¾ã®æåãè¿ã
次ã®ä¾ã¯ãæå®ããæååã®ä¸ã§æå¾ã«è¦ã¤ãã£ãæåãè¿ã颿°ã§ãã
// æå®ãããæååã®æå¾ã®æåãè¿ã颿°
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() ã¡ã½ããã®ç°¡æ½ãã¨èªã¿ããããéç«ã£ã¦ãã¾ãã
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® 2027 Language Specification> # sec-string.prototype.at> |