Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

How to Compare Strings Using localeCompare

/* locaelCompare returns:

1 if string1 is greater (higher in the alphabetical order) than string2
-1 if string1 is smaller (lower in the alphabetical order) than string2
0 if string1 and string2 are equal in the alphabetical order

*/

const string1 = "hello"
const string2 = "world"

const compareValue = string1.localeCompare(string2)
// -1

/*
It gives -1 because, in the English locale,
h in hello comes before w in the world
(w is further down in the alphabetical order than h)
*/

const string3 = "banana"
const string4 = "back"

const compareValue = string3.localeCompare(string4)
// 1

/*
The comparison above gives 1 because, in the English locale,
ban in banana comes after bac in back.
*/

const string5 = "fcc"
const string6 = "fcc"
const string7 = "Fcc"

const compareValue1 = string5.localeCompare(string6)
// 0

const compareValue2 = string5.localeCompare(string7)
// -1

/*
Comparing "fcc" and "fcc" gives 0 because they are equal in order.
"fcc" and "Fcc" gives -1 because capital "F" is greater than small "f".
*/
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #How #Compare #Strings #Using #localeCompare
ADD COMMENT
Topic
Name
2+4 =