.localeCompare()
is a JavaScript method that compares strings in the current locale. This method compares strings in three different ways with a return value for each comparison criterion.
The .localeComapre()
method has a syntax that can be split into three different syntaxes and still do the base job of comparing strings. This syntax is as follows:
localeCompare( stringToCompare, locales, option );
This can be used separately as follows:
.localeCompare(stringToCompare);
.localeCompare(stringToCompare, locales);
.localeCompare(stringToCompare, locales, options);
stringToCompare
: This is the string to be compared with another string to which the method is appended.
locales
: This is also called a language. If this is not specified, the method compares the string with the current locale, which is the browser’s default language.
options
: Various options relating to the punctuation, numeric, and sensitivity can be specified to tweak the result of the method and make it more perfect.
The .localeCompare()
method has three return values. These depend on the sort order of the strings to be compared, the locale, and the options specified when calling the method.
These return values are based on whether the reference string comes before, after, or is equivalent to the string compared to it.
0
if they are equivalent.Suppose we want to compare a string, CARe
, with another string, CarE
, to see if they contain the same letters using the localeCompare()
method.
Let’s check the code below:
myString
and assign a string, CARe
, to it.stringToCompare
, and assign another string, CarE
, to it.result
. This variable holds the return value of comparing the two other strings with the localeCompare()
method.This method uses a language, en
, that indicates English and two options: sensitivity; base
and ignorePunctuation
. sensitivity; base
makes it case-insensitive while ignorePunctuation: true
makes the method ignore punctuations.
console.log()
method.When we check the console, it returns an empty object equal to
0
. This indicates that both strings are equivalent.