The localeCompare() method checks if a given string comes before, after, or is equivalent as another string in sort order.
Example
localeCompare() Syntax
The syntax of the localeCompare() method is:
str.localeCompare(compareStr, locales, options)
Here, str is a string.
localeCompare() Parameters
The localeCompare() method takes in:
- compareStr - The string against which
stris compared. - locales and options (optional) - These arguments customize function by specifying what formatting conventions to use.
localeCompare() Return Value
The localeCompare() returns:
- -1 : if the reference string is sorted before compareStr.
- 0 : if two strings are equivalent.
- 1 : if the reference string is sorted after compareStr.
Note: Since the returned negative and positive integers vary between browsers, do not rely on exact values -1 or 1.
Example 1: Using localeCompare() Method
Output
1
In the above example, we have passed 'c' as a reference string and 'b' as a compare string and have assigned the return value of localeCompare() to result1.
Since the alphabet 'c' comes after 'b', 'c'.localeCompare('b') returns a positive number i.e. 1.
Example 2: Using localeCompare()
Output
-1
Here, we have passed 'b' as a reference string and 'c' as a compare string. Since the reference string comes before compareStr, 'b'.localeCompare('c') returns a negative value which is -1.
Example 3: localeCompare() With Equal Strings
Output
0 1
In the above example, we have compared two unequal strings 'Python' and 'JavaScript'. Since 'Python' comes after 'JavaScript', the method returns 1.
However, while comparing two equal strings 'JavaScript', the method returns 0.
Example 4: Using localeCompare() With locales and options
Output
-1 1 1 -1