← 返回首页
String.prototype.endsWith() - JavaScript | MDN

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

String.prototype.endsWith()

Baseline 広く利用可能

この機能は広く実装されており、多くのバージョンの端末やブラウザーで動作します。2015年9月以降、すべてのブラウザーで利用可能です。

endsWith()String 値のメソッドで、文字列が引数で指定された文字列で終わるかを判定して true か false を返します。

目次

試してみましょう

const str1 = "Cats are the best!"; console.log(str1.endsWith("best!")); // 予想される結果: true console.log(str1.endsWith("best", 17)); // 予想される結果: true const str2 = "Is this a question?"; console.log(str2.endsWith("question")); // 予想される結果: false

構文

js
endsWith(searchString) endsWith(searchString, endPosition)

引数

searchString

str の末尾で検索される文字の集合です。正規表現にすることはできません。正規表現ではない値はすべて文字列に変換されますので、省略したり undefined を渡したりすると、endsWith() は "undefined" という文字列を検索します。これはおそらく望むところではないでしょう。

endPosition 省略可

searchString が見つかると期待される末尾の位置(searchString の最後の文字 +1 のインデックス)です。既定値は str.length です。

返値

文字列が指定された文字列で終わる場合、searchString が空文字列の場合は true、それ以外の場合は false です。

例外

TypeError

searchString が正規表現であった場合。

解説

文字列が特定の文字列で終わるかどうかを判断できます。このメソッドでは(英文字の)大文字小文字は区別されます。

endsWith() の使用

js
const str = "To be, or not to be, that is the question."; console.log(str.endsWith("question.")); // true console.log(str.endsWith("to be")); // false console.log(str.endsWith("to be", 19)); // true

仕様書

仕様書
ECMAScript® 2027 Language Specification
# sec-string.prototype.endswith

ブラウザーの互換性

ブラウザー互換性一覧表を表示するには、JavaScript を有効にしてください。

関連情報