JavaScript/String/prototype/endsWith
表示
String.prototype.endsWith()
は、ある文字列が指定された検索文字列で終わるかどうかを判定するメソッドです。このメソッドは、文字列全体または指定された位置までの部分文字列が、検索文字列で終わる場合に true
を返します[1]。
構文
[編集]str.endsWith(searchString[,endPosition])
searchString
: 検索する文字列。endPosition
: (省略可能)検索を終了する位置。指定しない場合は文字列の長さが使用されます。
例
[編集]文字列の末尾を確認するプログラム
[編集]以下のプログラムは、endsWith()
を使用して文字列が特定の部分文字列で終わるかどうかを確認します。
conststr='Hello world';console.log(str.endsWith('world'));// trueconsole.log(str.endsWith('hello'));// falseconsole.log(str.endsWith('o',5));// true('Hello'の末尾を確認)
このプログラムでは、endsWith()
を使用して文字列の末尾または指定位置までの部分が特定の文字列で終わるかを確認しています。
ファイル拡張子を確認するプログラム
[編集]以下のプログラムは、ファイル名が特定の拡張子で終わるかどうかを確認します。
constfilename='document.pdf';console.log(filename.endsWith('.pdf'));// trueconsole.log(filename.endsWith('.txt'));// falseconsole.log(filename.endsWith('document',8));// true
このプログラムでは、endsWith()
を使用してファイル名の拡張子を確認しています。
注意点
[編集]- 大文字と小文字: 大文字と小文字を区別します。
- endPosition:
endPosition
が負の数の場合、0として扱われます。 - 範囲外:
endPosition
が文字列の長さより大きい場合、文字列の長さとして扱われます。 - 空文字列: 空文字列で検索すると常に
true
を返します。 - 正規表現: 正規表現を引数として使用するとエラーが発生します。
脚註
[編集]- ^これは、文字列が特定の部分文字列で終わるかどうかを確認するために使用されます。