localeCompare in JS(javascript)

·

2 min read

Table of contents

The localeCompare() method in JavaScript is utilized for comparing two strings within the current locale. This method returns a numeric value that indicates the positioning of a reference string relative to the provided string in terms of sorting 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

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

To understand more let's take another analogy, in the above example code, the output is -1. To understand this, let's imagine a dictionary in which you find these two words "about" and "aware", the position of "about" is before the "aware" that's why the output is -1

The localeCompare() method in JavaScript takes two arguments, which include:

  1. The reference string: This is the string being compared to the given string.

  2. The given string: This is the string being compared to the reference string.

Additionally, the localeCompare() method supports two optional arguments:

  1. Locale: This specifies the locale to be used for the string comparison. If this argument is not provided, the method will default to the current locale.

  2. Options: An object that allows you to specify additional options for the comparison. Some of the supported options are:

    • Sensitivity: This determines the sensitivity of the comparison, with "CI" for case-insensitive and "CC" for case-sensitive comparisons.

    • Numeric: This option determines whether the strings should be treated as numbers. If set to true, the strings will be compared as numbers, regardless of their actual content.

The localeCompare() method is a valuable tool for comparing strings in a locale-sensitive manner. It can be particularly useful for sorting strings according to a user's preferred language or for comparing 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