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.


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

Live Demo

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

            document.getElementById("test").innerHTML = result;

Updated on: 08-Jan-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started