JavaScript - Compare Two Strings
Last Updated :
25 Nov, 2024
Improve
These are the followings ways to compare two strings:
1. Using strict equality (===) operator
We have defined a function that compare two strings using the strict equality operator (===), which checks if both the value and the type of the operands are equal.
let str1 = "hello";
let str2 = "world";
if (str1 === str2) {
console.log("Equal");
} else if (str1 > str2) {
console.log("str1 is greater");
} else if (str1 < str2) {
console.log("str2 is greater");
}
Output
str2 is greater
2. Using localeCompare( ) method
The localeCompare( ) method, which compares two strings based on the locale-sensitive comparison rules and returns:
- A negative number if the first string comes before the second string.
- Zero if the strings are equal.
- A positive number if the first string comes after the second string.
let str1 = "apple";
let str2 = "banana";
let res = str1.localeCompare(str2);
if (res === 0) {
console.log("Strings are equal");
} else if (res < 0) {
console.log("str2 is greater");
} else if (res > 0) {
console.log("str1 is greater");
}
Output
str2 is greater
3. Using Regular Expression
Regular expressions compares two strings based on specific patterns or criteria. We can use Regular Expression to verify if two given strings are same or not. However, this method is not case sensitive.
let str1 = "Hello";
let str2 = "hello";
let regex = new RegExp(`^${str2}$`, 'i');
if (regex.test(str1)) {
console.log("Equal");
} else if (str1 > str2) {
console.log("str1 is greater");
} else {
console.log("str2 is greater");
}
Output
Equal