String localeCompare() Method with Example in JavaScript

JavaScript String localeCompare() Method: Here, we are going to learn about the localeCompare() method of the string in JavaScript with Example.
Submitted by Shivang Yadav, on February 23, 2020

JavaScript | String localeCompare() Method

The String.localeCompare() method in JavaScript is used to compare two strings in JavaScript. The result of the comparison will be,

  • Positive: str1 is lexicographically greater than str2.
  • Zero: str1 is equal to str2.
  • Negative: str1 is lexicographically smaller than str2.

Syntax:

    str1.localeCompare(str2);

Parameter(s):

The method accepts one parameter which is the string to be compared with the calling string.

Return value:

The return type of this method is number which is the result of the comparison.

Browser support: Chrome, Internet explorer, Mozilla, Safari, Opera mini.

Example 1:

<script>
	document.write("Hello".localeCompare("Hello") + "<br/>");
	document.write("hello".localeCompare("hello") + "<br/>");
	document.write("Hello".localeCompare("hello") + "<br/>");
	document.write("hello".localeCompare("Hello") + "<br/>");
	document.write("ABC".localeCompare("BCD") + "<br/>");
	document.write("BCD".localeCompare("ABC") + "<br/>");
	document.write("PREM".localeCompare("SHIVANG") + "<br/>"); 
</script>

Output

0
0
1
-1
-1
1
-1

Example 2:

<script>
    str1 = "include"
    str2 = "Help"
    
    result = str1.localeCompare(str2);
  
    if (result) {
        document.write(str1 + " is greater than " + str2 + "<br>");
    }
</script>

Output

include is greater than Help

JavaScript String Object Methods »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.