Skip to content

JavaScript compare two strings | Example code

  • by

Use the localeCompare() method to compare two strings in JavaScript. Generally, if the strings contain only ASCII characters, then use the === operator to check if they are equal.

JavaScript compares two strings

Simple example code check if two Strings are Equal in JavaScript. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2, and 1 if string 2 is sorted before string 1.

<!DOCTYPE html>
<html>
<body>
  <script>
   var string1 = "World";
   var string2 = "World";
   
   var result = string1.localeCompare(string2);

   console.log(result)

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

Output:

JavaScript compare two strings

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

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading