Open In App

Is there anything similar to PHP strcmp() function in JavaScript ?

Last Updated : 15 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

String comparison function is available in many languages like strcmp() in PHP, C, C++, (<, >, ==, !=) operators in Python etc. In JavaScript, to compare two string we use localCompare() method

The localCompare() method compares two strings in the present or current locale. It returns an integer to indicate whether the strings are equal, or, whether a string comes before or after of another string in sorted order.

Syntax

string1.localCompare(string2)

Return Value:  The localCompare() method returns 

  •  0, if the two strings: string1 and string2, are equal 
  • 1, if string1 is sorted after string2 
  • -1, if string1 is sorted before string2

Example:

JavaScript




<h1 style="color:green">
    GeeksforGeeks
</h1>
<p>
    Click the button to see the returned value
</p>
  
<p>string1 = "abc", string2 = "abc"</p>
<button onclick="Comparison1()">
    Compare
</button>
  
<p>string1 = "def", string2 = "abc"</p>
<button onclick="Comparison2()">
    Compare
</button>
  
<p>string1 = "abc", string2 = "bcd"</p>
<button onclick="Comparison3()">
    Compare
</button>
  
<p id="compare"></p>
  
<script>
    function Comparison1() {
        var string1 = "abc";
        var string2 = "abc";
        var return_val = string1.localeCompare(string2);
        document.getElementById("compare").innerHTML = 
          return_val;
    }
      
    function Comparison2() {
        var string1 = "def";
        var string2 = "abc";
        var return_val = string1.localeCompare(string2);
        document.getElementById("compare").innerHTML = 
          return_val;
    }
      
    function Comparison3() {
        var string1 = "abc";
        var string2 = "def";
        var return_val = string1.localeCompare(string2);
        document.getElementById("compare").innerHTML = 
          return_val;
    }
</script>


Output: 

Is there anything similar to PHP strcmp() function in JavaScript ?

Is there anything similar to PHP strcmp() function in JavaScript ?



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads