JavaScript String startsWith()
startsWith() 方法用來判斷字串是否以指定的子字串開頭,回傳 true 或 false。
語法:
str.startsWith(searchString[, position])
- searchString 是要檢查的開頭字串
- position 是可選的起始位置,預設為 0
- 回傳 true 表示是以該字串開頭;false 表示不是
用法:
'Hello World'.startsWith('Hello'); // true
'Hello World'.startsWith('World'); // false
'Hello World'.startsWith('hello'); // false(大小寫有別)
指定起始位置:
'Hello World'.startsWith('World', 6); // true(從位置 6 開始)
'Hello World'.startsWith('Hello', 0); // true
'Hello World'.startsWith('Hello', 1); // false
實際應用:
// 檢查 URL 協定
var url = 'https://example.com';
if (url.startsWith('https://')) {
console.log('安全連線');
} else if (url.startsWith('http://')) {
console.log('非安全連線');
}
// 檢查檔案類型
var filename = 'image_001.jpg';
if (filename.startsWith('image_')) {
console.log('這是圖片檔案');
}
// 過濾以特定前綴開頭的項目
var items = ['btn-primary', 'btn-secondary', 'text-red', 'btn-danger'];
var buttons = items.filter(function(item) {
return item.startsWith('btn-');
});
// ['btn-primary', 'btn-secondary', 'btn-danger']
startsWith() 是 ES6 新增的方法。這個方法是大小寫敏感的。