Home >>JavaScript String Methods >JavaScript String localeCompare() Method
JavaScript localeCompare() method is used to compare two given input strings in the current locale. It returns a number indicating if the given string comes before, after or is equal as the compareString in sort order.
Syntax:
string.localeCompare(compareString)
Parameter | Description |
---|---|
compareString | This is a required parameter. It defines the string to compare with. |
Method | Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
localeCompare() | YES | YES | YES | YES | YES |
Here is an example of localeCompare() method:
<html> <body> <ul> <li>Returns -1 if str1 is sorted before str2</li> <li>Returns 0 if the two strings are equal</li> <li>Returns 1 if str1 is sorted after str2</li> </ul> <p>Click the button to see the Output.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var str1 = "Abhi"; var str2 = "Jerry"; var n = str1.localeCompare(str2); document.getElementById("demo").innerHTML = n; } </script> </body> </html>
Click the button to see the Output.
Example 2:
<html> <body> <p>Click the button to see the Output.</p> <button onclick="myFunction1()">Try it</button> <p id="demo1"></p> <script> function myFunction1() { var str1 = "Jerry"; var str2 = "Abhi"; var n = str1.localeCompare(str2); document.getElementById("demo1").innerHTML = n; } </script> </body> </html>
Click the button to see the Output.