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

浏览器兼容性

另见