JavaScript(JS) string method - localeCompare

www.‮figi‬tidea.com

The localeCompare() method is a string method in JavaScript that is used to compare two strings based on the current locale. It returns a number indicating whether the string comes before, after, or is the same as the string provided as an argument, based on the sort order of the current locale.

Here is the syntax for the localeCompare() method:

str.localeCompare(compareString[, locales[, options]])

Here, str is the original string you want to compare, and compareString is the string you want to compare to. The optional locales parameter is an array or string containing one or more language tags, indicating the language or languages to use for the comparison. The optional options parameter is an object that can contain properties such as sensitivity and caseFirst, which control the behavior of the comparison.

The localeCompare() method returns a number indicating the sort order of the two strings. If str comes before compareString, it returns a negative number. If str comes after compareString, it returns a positive number. If the two strings are the same, it returns 0.

Here is an example of using the localeCompare() method:

let str1 = "apple";
let str2 = "banana";
let result = str1.localeCompare(str2);
console.log(result); // -1

In the example above, the localeCompare() method compares str1 to str2, and returns -1 because "apple" comes before "banana" in alphabetical order. The result would be different if a different locale was used, as the sort order can vary between locales.