JavaScript の endsWith() で文字列の末尾を調べる

JavaScript で文字列が指定した並びで終わるかを調べるには text.endsWith(suffix) を使います。一致すれば true、一致しなければ false を返します。第2引数の endPosition を指定すると、先頭から切り出した範囲の末尾を調べられます。

文字列の末尾が一致するか調べる

console.log('report.pdf'.endsWith('.pdf')); // true
console.log('report.PDF'.endsWith('.pdf')); // false
console.log('report.pdf '.endsWith('.pdf')); // false
console.log('abc'.endsWith('')); // true
try {
  'abc'.endsWith(/c/);
} catch (error) {
  console.log(error.name); // TypeError
}

大文字と小文字は区別され、空白も比較に含まれます。空の接尾辞は常に一致するため、入力を必須にする場合は呼び出す前に値を確認してください。検索引数に正規表現を渡すと TypeError が発生します。パターンを調べる場合は RegExp.test() を使います。比較の規則は ECMAScript · String.prototype.endsWith() に記載されています。

endPosition で比較範囲を指定する

endPosition は検査する先頭部分の長さです。3 を指定すると、インデックス 0、1、2 が含まれます。メソッドは値を整数に変換し、0 から text.length までの範囲に収めます。省略すると文字列全体を使います。

const text = 'abzcdz';
console.log(text.endsWith('z'));    // true   
console.log(text.endsWith('z', 2)); // false
console.log(text.endsWith('z', 3)); // true
console.log(text.slice(0, 3));     // 'abz'    

// endPosition
console.log(text.endsWith('z', 3.9));  // true
console.log(text.endsWith('z', -1));   // false
console.log(text.endsWith('z', 99));   // true
console.log('A🙂Z'.endsWith('🙂', 3)); // true
console.log('A🙂Z'.endsWith('🙂', 2)); // false

位置は UTF-16 コード単位で数えます。'A🙂Z' の絵文字は2単位なので、3 を指定すれば 'A🙂' が含まれ、2 では絵文字の途中で区切られます。利用者が見た目の文字数を入力する場合は、コード単位の境界に換算します。

ファイル名と URL パスの末尾を調べる

まず比較したい対象を決めます。URL のパスを調べる場合は、new URL(address).pathname を使うとクエリとフラグメントを除けます。相対 URL には new URL(path, base) のように基準 URL を指定します。URL Standard · URL.pathname

console.log('report.pdf'.endsWith('.pdf')); // true
console.log('report.pdf?download=1'.endsWith('.pdf')); // false
const url = new URL('/report.pdf?download=1#preview', 'https://example.com');
console.log(url.pathname.endsWith('.pdf')); // true
console.log('REPORT.PDF'.toLowerCase().endsWith('.pdf')); // true

サービス側で ASCII の拡張子の大文字と小文字を区別しないなら、ファイル名を小文字に変換してから .pdf と比較できます。一致で分かるのはファイル名の末尾です。アップロードを受け付ける場合は実際の形式を調べ、サーバー側の検証ルールを適用してください。

HTML のサンプルで終了位置を変える

下のコードを UTF-8 の string-ends-with.html として保存し、ブラウザーで開きます。初期値の abzcdz は z で終わるので true です。終了位置をオンにして 3 を指定すると、対象は abz になり、結果は変わりません。2 にすると ab が対象となり、false になります。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>文字列の末尾を確認</title>
</head>
<body>
<label for="text">元の文字列</label>
<input id="text" type="text" value="abzcdz">
<label for="suffix">接尾辞</label>
<input id="suffix" type="text" value="z">
<label><input id="use-end" type="checkbox"> 終了位置を使う</label>
<label for="end">終了位置</label>
<input id="end" type="number" min="0" step="1" value="3" disabled>
<pre id="output" aria-live="polite"></pre>
<script>
const text = document.querySelector('#text');
const suffix = document.querySelector('#suffix');
const useEnd = document.querySelector('#use-end');
const end = document.querySelector('#end');
const output = document.querySelector('#output');

function show() {
  const value = text.value;
  const target = suffix.value;
  end.disabled = !useEnd.checked;
  const position = Number(end.value);
  if (useEnd.checked && (end.value.trim() === '' ||
      !Number.isInteger(position) || position < 0)) {
    output.textContent = "終了位置には0以上の整数を入力してください。";
    return;
  }
  const checked = useEnd.checked ? value.slice(0, position) : value;
  const result = useEnd.checked
    ? value.endsWith(target, position) : value.endsWith(target);
  output.textContent = `検査対象: ${JSON.stringify(checked)}\n` +
    `検索する接尾辞: ${JSON.stringify(target)}\n` +
    `endsWith() の結果: ${result}`;
}

text.addEventListener('input', show);
suffix.addEventListener('input', show);
useEnd.addEventListener('change', show);
end.addEventListener('input', show);
show();
</script>
</body>
</html>

終了位置をオンにしたまま数値欄を空にすると、入力案内が表示されます。オフにすると全文を比較します。このサンプルは負数や小数を受け付けません。メソッド自体は値を整数に変換し、範囲内に収めます。接尾辞を空欄にした場合も確認できます。