JavaScript String localeCompare()
Example
Compare two strings in the current locale:
let str1 = "ab";
let str2 = "cd";
str1.localeCompare(str2) // Returns -1
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The localeCompare() method compares two strings in the current locale.
The locale is based on the language settings of the browser.
localeCompare() returns -1, 1, or 0 if the string
comes before, after, or is equal in sort order.
Browser Support
localCompare() is fully supported in all browsers:
| Chrome | IE | Edge | Firefox | Safari | Opera |
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
string.localeCompare(compareString)
Parameter Values
| Parameter | Description |
|---|---|
| compareString | Required. The string to compare with |
Technical Details
| Return Value: | A Number, indicating whether the reference string comes before, after or is the same as the compareString in sort order.
Returns one of three values:
|
|---|---|
| JavaScript Version: | ECMAScript 1 |
More Examples
Example
Compare two strings in the current locale:
let str1 = "cd";
let str2 = "ab";
str1.localeCompare(str2) // Returns 1
Try it Yourself »
Example
Compare two equal strings in the current locale:
let str1 = "ab";
let str2 = "ab";
str1.localeCompare(str2) // Returns 0
Try it Yourself »
Example
Compare two equal strings in the current locale:
let str1 = "A";
let str2 = "a";
str1.localeCompare(str2) // Returns 1
Try it Yourself »

