JS -- LocaleCompare

JS -- LocaleCompare

localecompare is a method in javaScript, used for string comparison, returning a result based on their lexicographical order (order of characters based on unicode values).

As a function, it takes in three parameters namely:

  1. String --- The string you want to compare

  2. locales (optional) -- A String with BCP 47 language tag or an array of such strings. It specifies the locale to be used.

  3. Options (optional) -- An object with comparison option such as : {sensitivity: "base").

const string1 = "Ann"

const string2 = "John"

const compareStrings = string1.localeCompare(string2, locales, options);

Compare string will return -1 because Ann will come before John

It compares two strings and return a value that indicates their relative order based on the locale and language settings often used in sorting.

LocaleCompare has 4 distinct state for comparison

  1. Default (case sensitive)

  2. Accent (accent sensitive)

  3. Case (case sensitive)

  4. Base (case Insensitive and accent insensitive)

Without further ado, let's look into some examples :

const string3 = "azu" -- fish -- Nigerian Native Language -- IGBO LANGUAGE

const string4 = "aja" -- sand -- Nigerian Native Language --- IGBO LANGUAGE

  1. Default

     console.log('Default:', string3.localeCompare(string4)); // Result: 1 (case-sensitive)
    
  2. Case

     console.log(
       'Case:',
       string3.localeCompare(string4, undefined, { sensitivity: 'case' })
     ); // Result: 1 (case-sensitive)Accent
    
  3. Accent

     console.log(
       'Accent:',
       string3.localeCompare(string4, undefined, { sensitivity: 'accent' })
     ); // Result: 1 (accent-sensitive)
    
  4. Base

     console.log(
       'Base:',
       string3.localeCompare(string4, undefined, { sensitivity: 'base' })
     ); // Result: 1 (case-insensitive and accent-insensitive)