Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

What is the best way to compare two strings in JavaScript?



To compare two strings in JavaScript, use the localeCompare() method. 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.

Example

You can try to run the following code to compare two strings

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <button onclick="compareStr()">Compare Strings</button>
      <p id="test"></p>
      <script>
         function compareStr() {
            var string1 = "World";
            var string2 = "World";
            var result = string1.localeCompare(string2);

            document.getElementById("test").innerHTML = result;
         }
      </script>
   </body>
</html>
Updated on: 2020-01-08T09:40:36+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements