文字列の部分文字列を返す
// ── 基本: 文字列の一部を取り出す ────────────────────────
const str = 'Hello World';
// slice(開始, 終了) ← 終了インデックスは「含まない」
console.log(str.slice(6)); // 'World' ← 6文字目以降を全部
console.log(str.slice(0, 5)); // 'Hello' ← 0〜4文字目(5は含まない)
console.log(str.slice(3, 7)); // 'lo W'
// ── マイナスで末尾から指定できる ─────────────────────
console.log(str.slice(-5)); // 'World' ← 末尾5文字
console.log(str.slice(-5, -1)); // 'Worl' ← 末尾5文字目〜末尾2文字目
// ── よくある使い方 ────────────────────────────────────
// ファイル名から拡張子を取得
const filename = 'document.pdf';
const lastDot = filename.lastIndexOf('.');
const ext = filename.slice(lastDot + 1); // 'pdf'
const name = filename.slice(0, lastDot); // 'document'
// 長いテキストを省略表示
function truncate(text: string, max: number) {
return text.length > max ? text.slice(0, max) + '...' : text;
}sliceは負のインデックスに対応しているため、substringより汎用的。末尾からの切り出しにはsliceを使う。