Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
communitycreator

How to use .localeCompare() for string comparison in JavaScript

Akande Olalekan Toheeb

Overview

.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.

Syntax

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:

  1. .localeCompare(stringToCompare);
  2. .localeCompare(stringToCompare, locales);
  3. .localeCompare(stringToCompare, locales, options);

Parameters

  • 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.

Return values

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.

  • It returns a negative integer if the reference string comes before the compared string.
  • It returns a positive integer if it comes after the compared string.
  • It returns 0 if they are equivalent.

Example

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:

Console
Compare the two strings

Explanation

  • Line 1: We create a variable myString and assign a string, CARe, to it.
  • Line 2: We create another variable, stringToCompare, and assign another string, CarE, to it.
  • Line 4: We create a variable, 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.

  • Line 5: The result is set to be printed on the console with the console.log() method.

When we check the console, it returns an empty object equal to 0. This indicates that both strings are equivalent.

RELATED TAGS

javascript
communitycreator

CONTRIBUTOR

Akande Olalekan Toheeb
RELATED COURSES

View all Courses

Keep Exploring