Movatterモバイル変換


[0]ホーム

URL:


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

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

View in EnglishAlways switch to English

String.prototype.endsWith()

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月⁩.

endsWith() 方法用于判断一个字符串是否以指定字符串结尾,如果是则返回true,否则返回false

尝试一下

const str1 = "Cats are the best!";console.log(str1.endsWith("best!"));// Expected output: trueconsole.log(str1.endsWith("best", 17));// Expected output: trueconst str2 = "Is this a question?";console.log(str2.endsWith("question"));// Expected output: false

语法

js
endsWith(searchString)endsWith(searchString, endPosition)

参数

searchString

要搜索的作为结尾的字符串,不能是正则表达式。所有非正则表达式的值都会被强制转换为字符串,因此如果该参数被省略或传入undefinedendsWith() 方法会在字符串中搜索"undefined",这通常不是你想要的。

endPosition可选

预期找到searchString 的末尾位置(即searchString 最后一个字符的索引加 1)。默认为str.length

返回值

如果被检索字符串的末尾出现了指定的字符串(包括searchString 为空字符串的情况),则返回true;否则返回false

异常

TypeError

如果searchString是一个正则表达式,则会抛出。

描述

这个方法可以让你确定一个字符串是否以另一个字符串结尾。该方法区分大小写。

示例

使用 endsWith()

js
const str = "生存还是毁灭,这是一个问题。";console.log(str.endsWith("问题。")); // trueconsole.log(str.endsWith("毁灭")); // falseconsole.log(str.endsWith("毁灭", 6)); // true

规范

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

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp