JavaScript String endsWith()

endsWith() 方法用來判斷字串是否以指定的子字串結尾,回傳 truefalse

語法:

str.endsWith(searchString[, length])
  • searchString 是要檢查的結尾字串
  • length 是可選的,指定要搜尋的字串長度(預設為整個字串長度)
  • 回傳 true 表示是以該字串結尾;false 表示不是

用法:

'Hello World'.endsWith('World'); // true
'Hello World'.endsWith('world'); // false(大小寫有別)
'Hello World'.endsWith('Hello'); // false

指定搜尋長度:

// 只檢查前 5 個字元
'Hello World'.endsWith('Hello', 5); // true
'Hello World'.endsWith('ello', 5); // true
'Hello World'.endsWith('World', 5); // false

實際應用:

// 檢查副檔名
const filename = 'document.pdf';
if (filename.endsWith('.pdf')) {
  console.log('這是 PDF 檔案');
}

// 檢查多種副檔名
function isImage(filename) {
  return (
    filename.endsWith('.jpg') ||
    filename.endsWith('.jpeg') ||
    filename.endsWith('.png') ||
    filename.endsWith('.gif')
  );
}

isImage('photo.jpg'); // true
isImage('doc.pdf'); // false

// 過濾特定結尾的檔案
const files = ['app.js', 'style.css', 'main.js', 'index.html'];
const jsFiles = files.filter(function (file) {
  return file.endsWith('.js');
});
// ['app.js', 'main.js']
endsWith() 是 ES6 新增的方法。這個方法是大小寫敏感的。