Javascript String localeCompare()

Introduction

Javascript String localeCompare() compares one string to another.

referenceStr.localeCompare(compareString[, locales[, options]])
  • compareString - the string against which the referring string is compared
  • locales - Optional, locale to use
  • options - Optional, option settings

It returns one of three values as follows:

ValueMeaning
a negative number If the string should come alphabetically before the string argument
0If the string is equal to the string argument.
a positive number If the string should come alphabetically after the string argument

Using localeCompare()

console.log('a'.localeCompare('c')); 
console.log('c'.localeCompare('C')); 
console.log('a'.localeCompare('a'));

localeCompare() enables a case-insensitive sort of an array.

var items = ['CSS', 'css', 'Java', 'javascript', 'SQL', 'sql'];
items.sort((a, b) => a.localeCompare(b, 'fr', {ignorePunctuation: true}));

Compare strings


let stringValue = "CSS";    
console.log(stringValue.localeCompare("HTML"));  
console.log(stringValue.localeCompare("CSS")); 
console.log(stringValue.localeCompare("Java")); 

function determineOrder(value) {
    let result = stringValue.localeCompare(value);
    if (result < 0) {
        console.log(`The string 'CSS' comes before the string '${value}'.`);
    } else if (result > 0) {
        console.log(`The string 'CSS' comes after the string '${value}'.`);
    } else {/* w ww.  j  a  va  2s .  com*/
        console.log(`The string 'CSS' is equal to the string '${value}'.`);
    }
}

determineOrder("HTML");
determineOrder("Java");
determineOrder("CSS");



PreviousNext

Related