How to compare a string based on locale information

Description

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.

var stringValue = "A"; 
console.log(stringValue.localeCompare("a")); //-32
console.log(stringValue.localeCompare("A")); //0 
console.log(stringValue.localeCompare("B")); //-1 
//from   w w w .  ja  v  a2  s. c o  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.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window