Home » JavaScript Tutorial

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 string 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.