JavaScript String localeCompare()
Examples
Compare "ab" with "cd":
let text1 = "ab";
let text2 = "cd";
let result = text1.localeCompare(text2);
Try it Yourself »
let text1 = "cd";
let text2 = "ab";
let result = text1.localeCompare(text2);
Try it Yourself »
More examples below.
Description
The localeCompare()
method compares two strings in the current locale.
The localeCompare()
method returns sort order -1, 1, or 0
(for before, after, or equal).
The current locale is based on the language settings of the browser.
Syntax
string.localeCompare(compareString)
Parameters
Parameter | Description |
compareString | Required. The string to compare with. |
Return Value
Type | Description |
A number | One of 3 values: -1 if the string is sorted before the compareString 0 if the two strings are equal 1 if the string is sorted after the compareString |
More Examples
let text1 = "ab";
let text2 = "ab";
let result = text1.localeCompare(text2);
Try it Yourself »
let text1 = "A";
let text2 = "a";
let result = text1.localeCompare(text2);
Try it Yourself »
Browser Support
localeCompare()
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.