JavaScript – Compare Strings

To compare two strings in JavaScript, we can use relational operators like less-than operator, greater-than operator, or equal-to operator.

Syntax

The boolean condition to check if string str1 is greater than string str2 is

str1 > str2

The boolean condition to check if string str1 is less than string str2 is

str1 < str2

The boolean condition to check if string str1 is equal to string str2 is

str1 == str2
ADVERTISEMENT

Examples

The following is a quick example to check if two strings are equal in JavaScript.

var str1 = 'apple';
var str2 = 'banana';
if (str1 > str2) {
    //str1 is greater than str2.
}
if (str1 < str2) {
    //str1 is less than str2.
}
if (str1 == str2) {
    //str1 is equal to str2.
}

We may also use if-else-if to combine these individual if statements.

var str1 = 'apple';
var str2 = 'banana';
if (str1 > str2) {
    //str1 is greater than str2.
} else if (str1 < str2) {
    //str1 is less than str2.
} else {
    //str1 is equal to str2.
}

In the following example, we take two strings in script, and compare these strings using relational operators.

index.html

Conclusion

In this JavaScript Tutorial, we learned how to compare strings in JavaScript, using relational operators, with examples.