DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on

What is localeCompare in JS(Javascript) ?

The localeCompare() method in JavaScript allows for comparing two strings within the current locale. By utilizing this method, you can obtain a numerical value that indicates the relative positioning of a reference string in relation to the provided string, determining whether it comes before, after, or is the same in terms of sort order

If you don't understand the above definition, don't worry. You will grasp the concept after reading the following example

The following are the possible return values of the localeCompare() method:

-1 - The reference string comes before the given string in sort order.

1 - The reference string comes after the given string in sort order.

0 - The reference string is the same as the given string.

Example:-

const str1 = "about";
const str2 = "aware";

const result = str1.localeCompare(str2);

console.log(result); // -1
Enter fullscreen mode Exit fullscreen mode

In this example, the localeCompare() method returns -1 because the string str1 comes before the string str2 in the current locale.

To gain a deeper understanding, let's explore another analogy. In the provided code example, the output is -1. To comprehend this, let's envision a dictionary where we encounter the words "about" and "aware." In this case, the position of "about" precedes "aware," which explains why the output is -1.

The localeCompare() method takes two arguments:

The reference string - The string that is being compared to the given string.
The given string - The string that is being compared to the reference string.

The localeCompare() method also supports two optional arguments:

locale - The locale that should be used to compare the strings. If this argument is not specified, the current locale will be used.
options - An object that specifies the options for the comparison. The following are the supported options:
sensitivity - The sensitivity of the comparison. The possible values are "CI" (case-insensitive) and "CC" (case-sensitive).
numeric - Whether to treat the strings as numbers. If this option is set to true, the strings will be compared as numbers, regardless of their content.

The localeCompare() method is a useful tool for comparing strings in a locale-sensitive way. It can be used to sort strings in a user's preferred language, or to compare strings that contain diacritics or other special characters.

Thank you for reading this blog, follow me on Twitter, I regularly share blogs and post on Javascript, React, Web development and opensource contribution

Twitter- https://twitter.com/Diwakar_766

Github- https://github.com/DIWAKARKASHYAP

Top comments (0)