Home Programs How to Compare Two Strings in JavaScript

How to Compare Two Strings in JavaScript

In this example we will compare 2 strings to see if they are a match

Example 1

First of all we convert the strings to lowercase using .toLowerCase() method, you can also convert to uppercase if you preferred using the toUpperCase() method.

We then compare these 2 strings using the strict equality operator ===

Depending on the result we display some text to the user

// string comparison
const string1 = 'maxJavascript Programs';
const string2 = 'maxjavascript programs';

// compare both strings
const result = string1.toLowerCase() === string2.toLowerCase();

if(result) 
{
    console.log('The strings are similar.');
} 
else 
{
    console.log('The strings are not similar.');
}

When you run this you will see something like this

The strings are similar.

Example 2

But what if you did not convert the string to lowercase or uppercase

// string comparison
const string1 = 'maxJavascript Programs';
const string2 = 'maxjavascript programs';

// compare both strings
const result = string1 === string2;

if(result) 
{
    console.log('The strings are similar.');
} 
else 
{
    console.log('The strings are not similar.');
}

When you run this you will see something like this

The strings are not similar.

It all depends whether you want to check for case sensitivity or not, especially important when taking user input.

You may also like