JavaScript String localeCompare() method
- Föregående sida length
- Nästa sida match()
- Åter till föregående nivå JavaScript String referens manual
Definition and usage
localeCompare()
The method compares two strings in the current language environment.
localeCompare()
The method returns the sorting order -1
,1
or 0
(Indicates before, after, or equal).
The current language environment is based on the browser's language settings.
Example
Example 1
Compare "ab" and "cd":
let text1 = "ab"; let text2 = "cd"; let result = text1.localeCompare(text2);
Example 2
let text1 = "cd"; let text2 = "ab"; let result = text1.localeCompare(text2);
Example 3
let text1 = "ab"; let text2 = "ab"; let result = text1.localeCompare(text2);
Example 4
let text1 = "A"; let text2 = "a"; let result = text1.localeCompare(text2);
Syntax
string.localeCompare(target)
Parameter
Parameter | Description |
---|---|
target | Required. The string to be compared. |
Return value
Type | Description |
---|---|
Number |
One of the 3 values:
|
Technical details
Return value
returns the number that indicates the comparison result.
If string less than targetThen localeCompare()
returns a number less than 0.
If string greater than targetThen this method returns a number greater than 0.
If two strings are equal, or do not differ according to the local sorting rules, this method returns 0.
Explain
to <
and >
When the operator is applied to a string, it compares strings using only the Unicode encoding of characters, without considering the local sorting rules. The order generated in this way may not be correct. For example, in Spanish, the character 'ch' is usually sorted as a character between 'c' and 'd'.
localeCompare()
method provides a way to compare strings, taking into account the default local sorting rules. The ECMAScript standard does not specify how to perform a local-specific comparison operation; it only specifies that this function uses the sorting rules provided by the underlying operating system.
Browser support
localeCompare()
is a feature of ECMAScript1 (ES1).
All web browsers fully support ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Stöd | Stöd | Stöd | Stöd | Stöd | Stöd |
- Föregående sida length
- Nästa sida match()
- Åter till föregående nivå JavaScript String referens manual