Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptWhat is the correct way to check for string equality in JavaScript...

What is the correct way to check for string equality in JavaScript ?

In this article, we will see the correct way to check for string equality in JavaScript. Whenever we need to compare the string we check for string equality by using different approaches. Strict equality operator is also one of the methods of comparison.

A few methods are explained below:

Method 1: Using strict equality operator

This operator checks for both value and type equality. it can be also called as strictly equal and is recommended to use it mostly instead of double equals

Example:

Javascript




const str1 = 'neveropen for neveropen';
const str2 = 'neveropen for neveropen';
 
if (str1 === str2) {
  console.log('The strings are equal ');
} else {
  console.log('The strings are not  equal');
}


Output:

The strings are equal 

Method 2: Using double equals (==) operator

This operator checks for value equality but not type equality. 

Example:

Javascript




const numStr = '42';
 
if (numStr == 42) {
  console.log('The values are equal');
} else {
  console.log('The values are not equal');
}


Output:

The strings are equal 

Method 3: Using String.prototype.localeCompare() method

This method compares two strings and returns a value indicating whether one string is less than, equal to, or greater than the other in sort order. 

Example:

Javascript




const str1 = 'hello';
const str2 = 'neveropen for neveropen';
 
const comparison = str1.localeCompare(str2);
 
if (comparison === 0) {
  console.log('The strings are equal');
} else {
  console.log('The strings are not equal');
}


Output:

The strings are not equal

Method 4: Using String.prototype.match() method

This method tests a string for a match against a regular expression and returns an array of matches. 

Example:

Javascript




const str1 = 'hello neveropen';
const str2 = 'hello neveropen';
 
const match = str2.match(str1);
 
if (match) {
    console.log('The strings are equal');
} else {
    console.log('The strings are not equal');
}


Output:

The strings are equal 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments