String.prototype.startsWith()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 2015 年 9 月以來,該特性已在各大瀏覽器中可用。

startsWith() 方法是 String 值的一個方法,它用於確定一個字串是否以另一個指定字串的字元開頭,並返回相應的 truefalse

試一試

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

異常

TypeError

如果 searchString 是正則表示式,則丟擲此錯誤。

描述

此方法可讓您確定一個字串是否以另一個字串開頭。此方法區分大小寫。

示例

使用 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

瀏覽器相容性

另見