How to compare two strings in JavaScript if the condition | Example

  • by

Use strict equality operators ( === ) to compare two strings in JavaScript if the condition. The “regular” == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

if (string1 === string2) {
  console.log("Matching strings!");
}
if (title === "LastName")
      doSomething();

Compare two strings in JavaScript if the condition

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    var string1 = "Hello World";
    var string2 = "Hello world.";
    
    if (string1 === string2) {
      console.log("Matching strings!");
    }
    else {
      console.log("Strings do not match");
    }

  </script>
</body>
</html> 

Output:

How to compare two strings in JavaScript if the condition

it is possible that there is whitespace to the left and or right of one string. So, just put a .trim() at the end of strings before comparing:

if(s1.trim() === s2.trim())
{
    // your code
}

Do comment if you have any doubts or suggestions on this JS compare string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.