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>
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>