Javascript - String localeCompare() Method

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

Description

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

The locale is based on the language settings of the browser.

The localeCompare() method returns a number indicating whether the string comes before, after or is equal as the compareString in sort order.

Return Value Meaning
-1if str1 is sorted before str2
0 if the two strings are equal
1 if str1 is sorted after str2

Syntax

string.localeCompare(compareString)

Parameter Values

Parameter Require Description
compareString Required. The string to compare with

Return

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:

  • -1 if the reference string is sorted before the compareString
  • 0 if the two strings are equal
  • 1 if the reference string is sorted after the compareString

Example

Compare two strings in the current locale:

Demo

//compare the two strings in the current locale.
var str1 = "ab";
var str2 = "cd";
var n = str1.localeCompare(str2);
console.log(n);/*from  w ww.j  ava 2  s.co  m*/

//compare two strings in the current locale.
var str1 = "cd";
var str2 = "ab";
var n = str1.localeCompare(str2);
console.log(n);

//Compare two equal strings in the current locale:
var str1 = "ab";
var str2 = "ab";
var n = str1.localeCompare(str2);
console.log(n);

Result