String.prototype.endsWith()
endsWith()
メソッドは文字列が引数で指定された文字列で終わるかを判定して true
か false
を返します。
試してみましょう
構文
str.endsWith(searchString[, length])
引数
searchString
-
str
の末尾で検索される文字の集合です。 length
省略可-
指定された場合、
str
の長さとして使用されます。既定値はstr.length
です。
返値
文字列が指定された文字列で終わる場合は true
、それ以外の場合は false
です。
解説
文字列が特定の文字列で終わるかどうかを判断できます。このメソッドでは (英文字の) 大文字・小文字は区別されます。
例
endsWith() の使用
let 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 6 で追加されました。すべての JavaScript の実装でまだ利用可能ではないかもしれません。しかしながら、次のコードで String.prototype.endsWith()
をエミュレートできます。
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
};
}
仕様書
Specification |
---|
ECMAScript Language Specification # sec-string.prototype.endswith |
ブラウザーの互換性
BCD tables only load in the browser