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 |
浏览器兼容性
加载中…