Table of contents
1.
Introduction
2.
Using Strict Equality (===) Operator
2.1.
Syntax
2.2.
Example 1: Comparing Identical Strings
2.3.
Example 2: Case Sensitivity
3.
Using localeCompare() Method
3.1.
Syntax
3.2.
Example 1: Comparing Strings Lexicographically
3.3.
Example 2: Ignoring Case Sensitivity
4.
Using Regular Expression
4.1.
Syntax
4.2.
Example 1: Checking for Exact Match
4.3.
Example 2: Case-Insensitive Comparison
5.
Check if a String Contains Another String  
5.1.
Using `includes()` Method  
5.2.
Using `indexOf()` Method  
6.
How to Compare two Strings in Javascript Using localeCompare()?
6.1.
Example: Advanced Comparison
7.
Frequently Asked Questions
7.1.
What is the difference between == and === for string comparison in JavaScript?
7.2.
How does localeCompare() handle case sensitivity?
7.3.
Can regular expressions compare strings for exact matches?
8.
Conclusion
Last Updated: Jan 25, 2025
Easy

Compare Two Strings in JavaScript

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Compare Two Strings in JavaScript is a common task in programming that involves checking whether two strings are identical or determining their differences. This feature is widely used in web development for functionalities like form validation, search filters, and data comparison. JavaScript provides various methods, such as the === operator, localeCompare(), and functions like toLowerCase() for case-insensitive comparisons, to make this task simple and effective.

Compare Two Strings in JavaScript

In this article, we will discuss different methods to compare two strings in JavaScript, including strict equality (===), localeCompare() method, and regular expressions. 

Using Strict Equality (===) Operator

The strict equality operator (===) is the simplest way to compare two strings in JavaScript. It checks whether two strings are identical in terms of both value and type. This method is case-sensitive, meaning uppercase and lowercase letters are treated as different.

Syntax

string1 === string2

Example 1: Comparing Identical Strings

const string1 = "hello";
const string2 = "hello";
if (string1 === string2) {
    console.log("The strings are identical.");
} else {
    console.log("The strings are different.");
}
You can also try this code with Online Javascript Compiler
Run Code


Output:

The strings are identical.

Example 2: Case Sensitivity

const string1 = "Hello";
const string2 = "hello";
if (string1 === string2) {
    console.log("The strings are identical.");
} else {
    console.log("The strings are different.");
}
You can also try this code with Online Javascript Compiler
Run Code


Output:

The strings are different.


This example demonstrates that === treats "Hello" and "hello" as different due to case sensitivity.

Using localeCompare() Method

The localeCompare() method compares two strings based on the current locale. It’s case-sensitive by default and is particularly useful for sorting strings or checking the order of strings in lexicographical order.

Syntax

string1.localeCompare(string2, locale, options)
  • locale: Optional. Specifies the locale for comparison. Defaults to the environment’s locale.
     
  • options: Optional. Additional settings for comparison (e.g., sensitivity).

Example 1: Comparing Strings Lexicographically

const string1 = "apple";
const string2 = "banana";
const result = string1.localeCompare(string2);
if (result === 0) {
    console.log("The strings are identical.");
} else if (result < 0) {
    console.log("string1 comes before string2.");
} else {
    console.log("string1 comes after string2.");
}
You can also try this code with Online Javascript Compiler
Run Code


Output:

string1 comes before string2.

Example 2: Ignoring Case Sensitivity

const string1 = "Hello";
const string2 = "hello";
const result = string1.localeCompare(string2, undefined, { sensitivity: "base" });

if (result === 0) {
    console.log("The strings are identical.");
} else {
    console.log("The strings are different.");
}
You can also try this code with Online Javascript Compiler
Run Code


Output:

The strings are identical.


This example shows how you can use localeCompare() to perform a case-insensitive comparison by setting the sensitivity option to base.

Using Regular Expression

Regular expressions (regex) are powerful tools for pattern matching and string manipulation. You can use them to compare strings based on specific patterns.

Syntax

regex.test(string)

Example 1: Checking for Exact Match

const string1 = "hello world";
const regex = /^hello world$/;

if (regex.test(string1)) {
    console.log("The string matches the pattern.");
} else {
    console.log("The string does not match the pattern.");
}
You can also try this code with Online Javascript Compiler
Run Code


Output:

The string matches the pattern.

Example 2: Case-Insensitive Comparison

const string1 = "Hello";
const regex = /^hello$/i;
if (regex.test(string1)) {
    console.log("The strings match (case-insensitive).");
} else {
    console.log("The strings do not match.");
}
You can also try this code with Online Javascript Compiler
Run Code


Output:

The strings match (case-insensitive).


Here, the i flag in the regex makes the comparison case-insensitive.

Check if a String Contains Another String  

One of the most common tasks when working with strings in JavaScript is checking if one string contains another. This is useful in scenarios like searching for keywords, validating user input, or filtering data. JavaScript provides several methods to achieve this, & we’ll discuss them in detail.  

Using `includes()` Method  

The `includes()` method is the simplest way to check if a string contains another string. It returns `true` if the string is found & `false` otherwise. Let’s see how it works:  

let mainString = "Hello, welcome to JavaScript programming!";
let searchString = "JavaScript";

if (mainString.includes(searchString)) {
    console.log("The string contains 'JavaScript'.");
} else {
    console.log("The string does not contain 'JavaScript'.");
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output

The string contains 'JavaScript'.


In this code:  

  • `mainString` is the string we’re searching in.  
     
  • `searchString` is the string we’re looking for.  
     
  • The `includes()` method checks if `searchString` exists in `mainString`.  
     
  • If it does, it logs "The string contains 'JavaScript'." Otherwise, it logs "The string does not contain 'JavaScript'."  

Using `indexOf()` Method  

Another way to check if a string contains another string is by using the `indexOf()` method. This method returns the index of the first occurrence of the search string. If the string is not found, it returns `-1`.  

let mainString = "Learning JavaScript is fun!";
let searchString = "fun";
if (mainString.indexOf(searchString) !== -1) {
    console.log("The string contains 'fun'.");
} else {
    console.log("The string does not contain 'fun'.");
}
You can also try this code with Online Javascript Compiler
Run Code

 

Output

The string contains 'fun'.


In this code:  

  • `indexOf()` searches for `searchString` in `mainString`.  
     
  • If the result is not `-1`, it means the string is found.  
     
  • This method is useful when you also need the position of the string.  

How to Compare two Strings in Javascript Using localeCompare()?

The localeCompare() method provides more advanced options for comparing strings beyond simple equality. Here are some steps to use it effectively:

  1. Understand the Result:
    • 0: The strings are equal.
       
    • Negative value: The first string comes before the second.
       
    • Positive value: The first string comes after the second.
       
  2. Set Options for Advanced Comparison: Use the options parameter to customize the comparison:
  • sensitivity: Determines case and accent sensitivity (e.g., base, accent, case).
     
  • ignorePunctuation: Ignores punctuation during comparison.

Example: Advanced Comparison

const string1 = "cafe";
const string2 = "café";
const result = string1.localeCompare(string2, "en", { sensitivity: "accent" });
if (result === 0) {
    console.log("The strings are identical.");
} else {
    console.log("The strings are different.");
}
You can also try this code with Online Javascript Compiler
Run Code


Output:

The strings are different.


In this example, the localeCompare() method recognizes the difference between "e" and "é" (e with an accent) when the sensitivity is set to accent

Frequently Asked Questions

What is the difference between == and === for string comparison in JavaScript?

The == operator compares values after type conversion, while === checks both value and type without any type conversion.

How does localeCompare() handle case sensitivity?

By default, localeCompare() is case-sensitive. However, you can customize it using the sensitivity option, such as setting it to base for case-insensitive comparisons.

Can regular expressions compare strings for exact matches?

Yes, regular expressions can compare strings for exact matches and also support advanced pattern matching. Use the test() method for this purpose.

Conclusion

Comparing two strings in JavaScript is an important skill that can be achieved using various methods. The strict equality operator (===) is ideal for exact, case-sensitive comparisons. The localeCompare() method is versatile and supports locale-sensitive comparisons with advanced options. Regular expressions offer flexibility for pattern matching and case-insensitive comparisons.

Live masterclass