What is the correct way to check for string equality in JavaScript ?
Last Updated :
13 Dec, 2023
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. A strict equality operator is also one of the methods of comparison.
A few methods are explained below:
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: In this example, we are checking the equality of the strings by using the strict equality (===) operator.
Javascript
const str1 = 'geeks for geeks' ;
const str2 = 'geeks for geeks' ;
if (str1 === str2) {
console.log( 'The strings are equal ' );
} else {
console.log( 'The strings are not equal' );
}
|
Output
The strings are equal
This operator checks for value equality but not type equality.
Example: In this example, we are checking the equality of the strings by using the double equals(==) operator.
Javascript
const numStr = '42' ;
if (numStr == 42) {
console.log( 'The values are equal' );
} else {
console.log( 'The values are not equal' );
}
|
Output
The values are equal
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: In this example, we are checking the equality of the strings.
Javascript
const str1 = 'hello' ;
const str2 = 'geeks for geeks' ;
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
This method tests a string for a match against a regular expression and returns an array of matches.
Example: In this example, we are checking the equality of the strings.
Javascript
const str1 = 'hello geeks' ;
const str2 = 'hello geeks' ;
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...