「JavaScript」localeCompare()で文字の並び順を比較する
構文
referenceStr.localeCompare(compareString)
referenceStr が compareString より前に出現するものである場合は負の数です。
referenceStr が compareString より後に出現するものである場合は正の数です。等しい場合は 0 です。
使用例
<!DOCTYPE html>
<html>
<head>
<style>
 body {
       white-space: pre-wrap ;
        background: #eeeeee; 
 }
</style>
</head>
<body>
<script>
let target= "study" ;
/*戻り値 1*/
let resA = target.localeCompare( "arkgame" ) ;
/*戻り値 0*/
let resB = target.localeCompare( "study" ) ;
/*戻り値 -1*/
let resC = target.localeCompare( "tech" ) ;
let results = { resA:resA, resB:resB,resC:resC } ;
/* for in文で要素を取得*/
for( var ele in results ) {
  document.body.appendChild( new Text("変数 " +ele + " = " +JSON.stringify(results[ele]) +"\n"));
}
</script>
</body>
</html>
結果
変数 resA = 1 変数 resB = 0 変数 resC = -1