How to compare two strings - JavaScript

Mo Ibra

Mo Ibra

Jan 6, 2023

In this article we will learn how to compare two strings in JavaScript.

It is very common to compare two strings in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to compare two strings.

There are many ways to compare strings in JavaScript such as:

  • Using localeCompare method
  • Using Mathematical Operators

Compare two string using localeCompare

We can compare two strings using localeCompare.

Let's see an example

// Strings
const firstString = "A";
const secondString = "Z";

// Compare
const compare = firstString.localeCompare(secondString)

// Result:
console.log(compare);

Output

-1

Result was -1 because secondString greater than firstString in the alphabetical order.

Another Example

// Strings
const firstString = "Z";
const secondString = "A";

// Compare
const compare = firstString.localeCompare(secondString)

// Result:
console.log(compare);

Output

1

Result was 1 because firstString greater than secondString in the alphabetical order.

What about if two strings are equal?

// Strings
const firstString = "A";
const secondString = "A";

// Compare
const compare = firstString.localeCompare(secondString)

// Result:
console.log(compare);

Output

0

locaelCompare returns:

  • 1 if firstString is greater than secondString
  • -1 if firstString is smaller than secondString
  • 0 if firstString and secondString are equal in the alphabetical order.

Compare two strings using Mathematical Operators

You can also use mathematical operators when comparing strings.

Example

// Strings
const firstString = "A";
const secondString = "Z";

// Tests:
console.log(firstString > secondString);
console.log(firstString < secondString);
console.log(firstString == secondString);

Output

false
true
false

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: