Compare Two Strings in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to compare two strings in JavaScript. For this, we can use

  • Comparison === operator
  • localeCompare() function

Syntax

string1 === string2                           // returns true or false
string1.localeCompare(string2)         // returns 0 or 1

Example 1: Using String Comparison === Operator

// program to compare two strings

const string1 = 'Hello World';
const string2 = 'Hello World';
const string3 = 'hello World';

const result1 = string1 === string2;
const result2 = string1 === string3;

console.log(result1);
console.log(result2);

Output

true
false

Example 2: Using localeCompare() Function

// program to compare two strings

const string1 = 'Hello World';
const string2 = 'Hello World';
const string3 = 'hello World';

const result1 = string1.localeCompare(string2);
const result2= string1.localeCompare(string3);

console.log(result1);
console.log(result2);

Output

0
1