どうも、ちょげ(@chogetarou)です。
文字列(string)の末尾の文字を取得する方法を紹介します。
方法

文字列(string)の末尾の文字を取得する方法は、3つあります。
slice()
1つ目は、slice()を使う方法です。
まず、文字列からslice()を呼び出します。
そして、slice()の引数に「−1」を指定します。
const last = text.slice(-1);
上記のslice()は、呼び出した文字列の最後の文字を取得します。
使用例
const text = "Hello,World";
const last = text.slice(-1);
console.log(text);
console.log(last);
出力:
Hello,World
d
インデックス
2つ目は、インデックスを使う方法です。
具体的には、文字列の末尾のインデックスにアクセスします。
末尾のインデックスは、文字列のlengthプロパティを「-1」して取得します。
const last = text[text.length - 1];
使用例
const text = "Hello,World";
const last = text[text.length - 1];
console.log(text);
console.log(last);
出力:
Hello,World
d
charAt()
3つ目は、charAt()を使う方法です。
まず、文字列からcharAt()を呼び出します。
そして、charAt()の引数にlengthプロパティを「-1」したい値を指定します。
const last = text.charAt(text.length - 1);
上記のcharAt()は、呼び出した文字列の最後の文字を取得します。
使用例
const text = "Hello,World";
const last = text.charAt(text.length - 1);
console.log(text);
console.log(last);
出力:
Hello,World
d
まとめ
文字列(string)の最後の文字を取得する方法は、次の3つです。
- slice()を使う方法
const last = text.slice(-1);
- インデックスを使う方法
const last = text[text.length - 1];
- charAt()を使う方法
const last = text.charAt(text.length - 1);
コメント