JavaScript Method:localeCompare
Lately I’ve been thinking that since Java has an equalsIgnoreCase method, JavaScript must have something similar. This is what I found: the localeCompare
method.
Structure
1 | str1.localeCompare(str2, [locales], [options]) |
Note: The Linux commands also has a locale
command!
Available locales
language
'en': English
'fr': French
'de': German
'es': Spanish
'ja': Japanese
'zh': Chinese
'ar': Arabic
'ru': Russian
We can also use a combination of language
and region
subtags to specify a more specific locale. For example:
'en-US': English (United States)
'fr-CA': French (Canada)
'de-DE': German (Germany)
'es-MX': Spanish (Mexico)
'ja-JP': Japanese (Japan)
'zh-CN': Chinese (China)
'ar-EG': Arabic (Egypt)
'ru-RU': Russian (Russia)
Available options
numeric
1 | console.log("60".localeCompare("40", undefined, { numeric: true })) // 1 |
numeric
can take one of the two values: true
and false
1 | console.log("60".localeCompare("100", undefined, { numeric: false })) // 1 |
With false
, both 60
and 100
are treated as normal String objects.
sensitivity
sensitivity
can take one of the three values: base
, accent
, case
1 | console.log("café".localeCompare("Cafe", undefined, { sensitivity: "base" })) // 0 |
caseFirst
The caseFirst
option in the localeCompare()
method specifies whether uppercase letters should come before or after lowercase letters in the sort order. It can take one of the following two values:
upper
: Sort uppercase letters before lowercase letters.
lower
: Sort lowercase letters before uppercase letters.
1 | console.log("Ba".localeCompare("AB", undefined, { sensitivity: "case" })) // 1 |
ignorePunctuation
The ignorePunctuation
option in the localeCompare()
method specifies whether punctuation and other symbols should be ignored during the comparison.
It can take one of the following two values: true
and false
1 | console.log("Hello, world!".localeCompare("Hello world", undefined, { ignorePunctuation: true })) // 0 |