JavaScript String localeCompare() method

Definition and usage

localeCompare() The method compares two strings in the current locale.

localeCompare() The method returns the sorting order -1,1 or 0(indicating before, after, or equal).

The current locale is based on the language setting of the browser.

Instance

Example 1

Compare "ab" and "cd":

let text1 = "ab";
let text2 = "cd";
let result = text1.localeCompare(text2);

Try it yourself

Example 2

let text1 = "cd";
let text2 = "ab";
let result = text1.localeCompare(text2);

Try it yourself

Example 3

let text1 = "ab";
let text2 = "ab";
let result = text1.localeCompare(text2);

Example 4

Try it yourself

let text1 = "A";
let text2 = "a";
let result = text1.localeCompare(text2);

Try it yourself

Syntax

string.localeCompare(target)

Parameter

Parameter Description
target Required. The string to be compared.

return value

Type Description
Number

One of the following 3 values:

  • -1, if the string is placed before the target
  •  0, if the two strings are equal
  •  1, if the string is placed after the target

Technical details

return value

returns a number indicating 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 there is no difference according to the local sorting rules, this method returns 0.

description

put < and > When the operator is applied to a string, it compares strings using the Unicode encoding of characters and does not consider 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 with consideration of the default locale sorting rules. The ECMAScript standard does not specify how to perform locale-specific comparison operations; it only specifies that this function uses the sorting rules provided by the underlying operating system.

Browser support

localeCompare() is an ECMAScript1 (ES1) feature.

All browsers fully support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support

Related Pages

JavaScript String

JavaScript String Methods

JavaScript String Search