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

文字列(string)の最後からN文字を取得する方法は、2つあります。
slice()
1つは、slice()を使う方法です。
まず、文字列からslice()を呼び出します。
そして、slice()の引数に取得する文字数のマイナスの値を指定します。
//N=取得する文字数
const last = text.slice(-N);
上記のslice()は、呼び出した文字列の最後からN文字を取得します。
使用例
const text = "Hello,World";
const last = text.slice(-5);
console.log(text);
console.log(last);
出力:
Hello,World
World
substring()
もう1つは、substring()を使う方法です。
まず、文字列からsubstring()を呼び出します。
そして、substring()の引数に、文字列のlengthプロパティ取得する文字数で引いた値を指定します。
//N=取得する文字数
const last = text.substring(text.length - N);
上記のsubstring()は、呼び出した文字列の最後からN文字を取得します。
使用例
const text = "Hello,World.";
const last = text.substring(text.length - 6);
console.log(text);
console.log(last);
出力:
Hello,World
World.
まとめ
文字列(string)の最後からN文字を取得する方法は、次の2つです。
- slice()を使う方法
const last = text.slice(-N);
- reverse()を使う方法
const last = text.substring(text.length - N);
コメント