Javascript Reference - JavaScript String localeCompare() Method








localeCompare() compares two strings and returns:

  • If the string is alphabetically before the string argument, a negative number is returned.
  • If the strings are equal, 0 is returned.
  • If the string is alphabetically after the string argument, a positive number is returned.

Browser Support

localeCompare() Yes Yes Yes Yes Yes




Syntax

string.localeCompare(anotherString);

Parameter Values

Parameter Description
anotherString Required. The string to compare

Return Value

Returns one of three values:

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




Example


var stringValue = "A"; 
console.log(stringValue.localeCompare("a")); //-32
console.log(stringValue.localeCompare("A")); //0 
console.log(stringValue.localeCompare("B")); //-1 
/*from ww  w  . j a v  a 2 s .co  m*/
function determineOrder(value) { 
    var result = stringValue.localeCompare(value); 
    if (result < 0){
        console.log("before"); 
    } else if (result > 0) { 
        console.log("after"); 
    } else { 
        console.log("equal"); 
    } 
}
determineOrder("a"); 
determineOrder("A"); 
determineOrder("B"); 

The code above generates the following result.