Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 标准内置对象
  5. String
  6. String.prototype.startsWith()

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

String.prototype.startsWith()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年9月.

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

尝试一下

const str1 = "Saturday night plans";console.log(str1.startsWith("Sat"));// Expected output: trueconsole.log(str1.startsWith("Sat", 3));// Expected output: false

语法

js
startsWith(searchString)startsWith(searchString, position)

参数

searchString

要在该字符串开头搜索的子串。不能是正则表达式。所有不是正则表达式的值都会被强制转换为字符串,因此省略它或传递undefined 将导致startsWith() 搜索字符串"undefined",这应该不是你想要的结果。

position可选

searchString 期望被找到的起始位置(即searchString 的第一个字符的索引)。默认为0

返回值

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

异常

TypeError

如果searchString正则表达式,则抛出该异常。

描述

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

示例

使用 startsWith()

js
const str = "To be, or not to be, that is the question.";console.log(str.startsWith("To be")); // trueconsole.log(str.startsWith("not to be")); // falseconsole.log(str.startsWith("not to be", 10)); // true

规范

Specification
ECMAScript® 2026 Language Specification
# sec-string.prototype.startswith

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp