String.prototype.startsWith()
startsWith() 方法是 String 值的一個方法,它用於確定一個字串是否以另一個指定字串的字元開頭,並返回相應的 true 或 false。
試一試
const str = "Saturday night plans";
console.log(str.startsWith("Sat"));
// Expected output: true
console.log(str.startsWith("Sat", 3));
// Expected output: false
語法
js
startsWith(searchString)
startsWith(searchString, position)
引數
searchString-
要在字串開頭搜尋的字元。不能是 正則表示式。所有不是正則表示式的值都會被 強制轉換為字串,因此省略此引數或傳遞
undefined會導致startsWith()搜尋字串"undefined",這通常不是您想要的結果。 position可選-
預計在
searchString找到的起始位置(searchString第一個字元的索引)。預設為0。
返回值
如果找到指定的字元開頭,則為 true,包括 searchString 為空字串的情況;否則為 false。
異常
描述
此方法可讓您確定一個字串是否以另一個字串開頭。此方法區分大小寫。
示例
使用 startsWith()
js
const str = "To be, or not to be, that is the question.";
console.log(str.startsWith("To be")); // true
console.log(str.startsWith("not to be")); // false
console.log(str.startsWith("not to be", 10)); // true
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string.prototype.startswith |
瀏覽器相容性
載入中…