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:
String --- The string you want to compare
locales (optional) -- A String with BCP 47 language tag or an array of such strings. It specifies the locale to be used.
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
Default (case sensitive)
Accent (accent sensitive)
Case (case sensitive)
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
Default
console.log('Default:', string3.localeCompare(string4)); // Result: 1 (case-sensitive)
Case
console.log( 'Case:', string3.localeCompare(string4, undefined, { sensitivity: 'case' }) ); // Result: 1 (case-sensitive)Accent
Accent
console.log( 'Accent:', string3.localeCompare(string4, undefined, { sensitivity: 'accent' }) ); // Result: 1 (accent-sensitive)
Base
console.log( 'Base:', string3.localeCompare(string4, undefined, { sensitivity: 'base' }) ); // Result: 1 (case-insensitive and accent-insensitive)