部分文字列の最初・最後の出現インデックスを返す
// ── 基本: 文字列の「位置(番号)」を調べる ──────────────
const text = 'hello world hello';
// indexOf: 前から探して最初に見つかった位置を返す
console.log(text.indexOf('hello')); // 0 ← 先頭から
console.log(text.lastIndexOf('hello')); // 12 ← 末尾から
console.log(text.indexOf('xyz')); // -1 ← 見つからない
// ── 「含むかどうか」のチェックにも使える ─────────────
if (text.indexOf('world') !== -1) {
console.log('worldが含まれている');
}
// ← includes() の方が読みやすいので現代はこちらが推奨
text.includes('world'); // true
// ── よくある使い方: 拡張子を取り出す ─────────────────
const filename = 'photo.vacation.jpg';
const lastDot = filename.lastIndexOf('.'); // 最後の . の位置
const ext = filename.slice(lastDot + 1); // 'jpg'
const name = filename.slice(0, lastDot); // 'photo.vacation'含有チェックだけならincludes()のほうが可読性が高い。位置が必要な場合にindexOfを使う。