SYNCERのロゴ
アイキャッチ画像

String.prototype.endsWith() - 末尾の文字と一致するか確認する

String.prototype.endsWith()は、元の文字の末尾の文字が、引数の文字と一致するか否かを確認するメソッドです。大文字、小文字は区別されます。

概要

名前
endsWith
所属
String.prototype
仕様書
https://tc39.github.io/ecma262/#sec-string.prototype.endswith

説明

String.prototype.endsWith ( searchString [ , endPosition ] )

第1引数(searchString)には、比較対象の文字列を指定する。1文字でなくてもいい。

第2引数(endPosition)には、任意で末尾文字扱いにする位置を指定する。位置は区切り線をどこに入れるかで考えると分かりやすい。負の数は指定できない。

文字列が末尾と一致した場合はtrue、それ以外はfalseが返る。

終了位置の指定
終了位置の指定

チュートリアル

引数の文字が、末尾と一致するかを確認します。

var string = "SYNCER" ;

string.endsWith( "CER" ) ;	// true
string.endsWith( "NCE" ) ;	// false

第2引数に位置を指定すると、その位置が末尾文字の扱いになります。例えば、下記では5を指定したため、5文字目が末尾扱いとなります。つまり、元の文字列は"SYNCE"として比較されるということです。

var string = "SYNCER" ;

string.endsWith( "CER", 5 ) ;	// false
string.endsWith( "NCE", 5 ) ;	// true

デモ

String.prototype.endsWith()のデモです。

<!-- このコードは編集できます。 -->

<!DOCTYPE html>
<html>
<head>
	<style>
body {
	white-space: pre-wrap ;
}
	</style>
</head>
<body>
<script>
/** try it! **/
var string = "SYNCER" ;

var a = string.endsWith( "CER" ) ;
var b = string.endsWith( "NCE" ) ;
var c = string.endsWith( "CER", 5 ) ;
var d = string.endsWith( "NCE", 5 ) ;
/** try it! **/

var results = { a:a, b:b, c:c, d:d, } ;

for( var name in results ) {
	console.log( name, results[name] ) ;
	document.body.appendChild( new Text( name + " = " + JSON.stringify( results[name] ) + "\n" ) ) ;
}
</script>
</body>
</html>

サポート状況

ChromeFirefoxSafariEdgeIEOperaiOS SafariAndroid
41+ 17+ 9.1+× 28+ 9.1+×
  • Twitterでシェア
  • Facebookでシェア
  • Google+でシェア
  • はてなブックマークでシェア
  • pocketに保存
  • LINEでシェア
更新履歴
2017年9月29日 (金)
コンテンツを公開しました。