3 Example(s) of JavaScript localeCompare function


Description :

JavaScript localeCompare function returns a number and tell whether string comes before, after or is the same as the compareString in sort order and this returns one of three values: -1 if the reference string is sorted before the 2nd string 0 if the two strings are equal 1 if the reference string is sorted after the 2nd string See the code snippet:


JavaScript localeCompare function Example - 1
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="compareStrings()">Compare the strings</button>
<p id="sample"></p>
<script>
function compareStrings() {
    var str1 = "Michael";
    var str2 = "Voughan";
    var n = str1.localeCompare(str2);
    document.getElementById("sample").innerHTML = n;
}
</script>

</body>
</html>

Output

Description :

JavaScript localeCompare function will return 0 because str1 and str2 are same.


JavaScript localeCompare function Example - 2
<!DOCTYPE html>
<html>
<head>
 <title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="compareString()">Compare Strings</button>
<p id="sample"></p>
<script>
function compareString() {
    var str1 = "LearnKode";
    var str2 = "LearnKode";
    var result = str1.localeCompare(str2);
    document.getElementById("sample").innerHTML = result;
}
</script>

</body>
</html>

Output

Description :

JavaScript localeCompare function will return 

  • -1 if the string1 is sorted before the string2
  • 0 if the two strings are equal
  • 1 if the reference string1 is sorted after the string2



JavaScript localeCompare function Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
      <script>
         var str1 = new String( "This is beautiful string" );
         var index = str1.localeCompare( "XYZ" );
         document.write("localeCompare first :" + index ); 
         document.write("<br />" ); 
         var index = str1.localeCompare( "AbCD ?" );
         document.write("localeCompare second :" + index ); 
      </script>
  </body>
</html>

Output