大网数据广告活动
Web 标准与前端开发

String.prototype.startsWith()

· 52CE 我爱测

String 的 **`startsWith()`** 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 `true` 或 `false`。

String 的 startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false。

JavaScript Demo: String.startsWith()

const str1 = "Saturday night plans";

console.log(str1.startsWith("Sat"));
// Expected output: true

console.log(str1.startsWith("Sat", 3));
// Expected output: false

语法

startsWith(searchString)
startsWith(searchString, position)

参数

  • searchString
    • : 要在该字符串开头搜索的子串。不能是正则表达式。所有不是正则表达式的值都会被强制转换为字符串,因此省略它或传递 undefined 将导致 startsWith() 搜索字符串 "undefined",这应该不是你想要的结果。
  • position
    • : searchString 期望被找到的起始位置(即 searchString 的第一个字符的索引)。默认为 0。

返回值

如果给定的字符在字符串的开头被找到(包括当 searchString 是空字符串时),则返回 true;否则返回 false。

异常

  • TypeError

描述

这个方法能够让你确定一个字符串是否以另一个字符串开头。这个方法区分大小写。

示例

使用 startsWith()

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

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。