Check if Strings are Equal in JavaScript
These are the following ways to check for string equality in JavaScript:
1. Using strict equality operator - Mostly Used
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.
let s1 = 'abc';
let s2 = 'abc';
if (s1 === s2) {
console.log('Equal');
} else {
console.log('Not Equal');
}
Output
Equal
2. Using double equals (==) operator
This operator checks for value equality but not type equality. we are checking the equality of the strings by using the double equals(==) operator.
let s1 = '42';
let s2 = '42';
if (s1 == s2) {
console.log('Equal');
} else {
console.log('Not Equal');
}
Output
Equal
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.
let s1 = 'hello';
let s2 = 'geeks for geeks';
let res = s1.localeCompare(s2);
if (res === 0) {
console.log('Equal');
} else {
console.log('Not Equal');
}
Output
Not Equal
4. Using String.prototype.match() method
This method tests a string for a match against a regular expression and returns an array of matches.
let s1 = 'hello geeks';
let s2 = 'hello geeks';
let res = s2.match(s1);
if (res) {
console.log('Equal');
} else {
console.log('Not Equal');
}
Output
Equal
5. Using String.prototype.includes() Method
The includes() method can determine whether one string contains another string. While it is not specifically designed for strict equality checks, it can be adapted for such purposes by ensuring both strings are fully contained within each other.
let s1 = 'hello geeks';
let s2 = 'hello geeks';
if (s1.includes(s2) && s2.includes(s1)) {
console.log('Equal');
} else {
console.log('Not Equal');
}
Output
Equal