JavaScript localeCompare()
The localeCompare()
method in JavaScript compares two strings and returns a value indicating whether one string comes before, after, or is the same in order as the other string, based on the language settings of the user. This method is useful when sorting strings in different languages.
Syntax
string.localeCompare(compareString[, locales[, options]])
compareString
: The string to compare with the base string.locales
: Optional. A string or an array of strings representing the locales to use for the comparison. If not specified, the default locale of the user is used.options
: Optional. An object containing additional options for the comparison, such assensitivity
,usage
, andnumeric
.
Example
const str1 = "apple";
const str2 = "banana";
console.log(str1.localeCompare(str2));
// output: -1 (str1 comes before str2 in alphabetical order)
Output
The output of localeCompare()
method is an integer that indicates the order of the string comparison. The return value can be one of these three possible values:
-1
: The base string is sorted before the compare string.0
: The base string and compare string are equivalent.1
: The base string is sorted after the compare string.