Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptIs there anything similar to PHP strcmp() function in JavaScript ?

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

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">
    neveropen
</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 ?

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments