JavaScriptで文字列内の特定の文字やパターンの最後の出現位置を見つけたい場合、`lastIndexOf()`メソッドを使用します。このメソッドは、String型のプロトタイプメソッドとして提供されており、文字列の後ろから検索を行います。

lastIndexOf()メソッドの基本的な使い方

const text = "Hello World Hello";
const position = text.lastIndexOf("Hello");
console.log(position); // 12

このメソッドは、検索文字列が見つからない場合は `-1` を返します。

構文

string.lastIndexOf(searchValue[, fromIndex])
  • `searchValue`: 検索する文字列
  • `fromIndex`: 検索を開始する位置(オプション)

具体的な使用例

基本的な検索

const str = "JavaScript programming";
console.log(str.lastIndexOf("a")); // 3

検索開始位置の指定

const text = "Hello World Hello";
console.log(text.lastIndexOf("Hello", 10)); // 0

存在しない文字列の検索

const str = "JavaScript";
console.log(str.lastIndexOf("Python")); // -1

大文字・小文字の区別

`lastIndexOf()`は大文字と小文字を区別します。

const str = "JavaScript";
console.log(str.lastIndexOf("script")); // -1
console.log(str.lastIndexOf("Script")); // 4

実践的な使用例

ファイル拡張子の取得

const filename = "document.test.pdf";
const lastDotPosition = filename.lastIndexOf(".");
const extension = filename.slice(lastDotPosition + 1);
console.log(extension); // "pdf"

最後のスラッシュ以降の文字列を取得

const path = "/user/documents/file.txt";
const lastSlashPosition = path.lastIndexOf("/");
const filename = path.slice(lastSlashPosition + 1);
console.log(filename); // "file.txt"

注意点

1. 大文字と小文字を区別しない検索が必要な場合は、文字列を事前に`toLowerCase()`で変換する必要があります。

const str = "JavaScript JAVASCRIPT javascript";
const searchTerm = "javascript";
const position = str.toLowerCase().lastIndexOf(searchTerm.toLowerCase());
console.log(position); // 20

2. `fromIndex`が負の値の場合、0から検索を開始します。

const str = "Hello World";
console.log(str.lastIndexOf("o", -5)); // -1

3. `fromIndex`が文字列の長さを超える場合、文字列全体を検索します。

const str = "Hello World";
console.log(str.lastIndexOf("o", 100)); // 7

まとめ

`lastIndexOf()`メソッドは、文字列内で特定のパターンの最後の出現位置を効率的に見つけることができます。ファイル名の操作やパス文字列の処理など、実践的なシーンで活用できる便利なメソッドです。大文字と小文字を区別する点や、検索開始位置の指定に関する動作を理解することで、より効果的に使用することができます。