JavaScript(JS) JS compare two strings
To compare two strings in JavaScript/JS, you can use the ===
operator, which checks if two values are equal and of the same type. Here's an example:
const string1 = "Hello"; const string2 = "hello"; if (string1 === string2) { console.log("The strings are equal."); } else { console.log("The strings are not equal."); }
In this example, we have two strings, string1
and string2
. We use the ===
operator to compare them. Since the two strings have different capitalization, the comparison will return false
.
We then use an if
statement to check if the strings are equal. If they are, we log a message to the console saying that the strings are equal. Otherwise, we log a message saying that the strings are not equal.
Note that the ===
operator checks for strict equality, meaning that it compares the values and types of the two operands. If you want to compare two strings in a case-insensitive way, you can convert them to the same case (e.g. lowercase or uppercase) using the toLowerCase()
or toUpperCase()
method before comparing them.