JavaScript String Compare

The JavaScript LocaleCompare function is one of the JavaScript String compare Function, which is used to compare two strings and check whether the two strings are equal or not?.

The LocaleCompare method will perform string comparison based on local language settings and returns any of the following three values:

  • Returns -1 if String_Object1 sorts before the String_Object2
  • Returns +1 if String_Object1 sorts after the String_Object2
  • It will return 0 if String_Object1 and String_Object2 are equal

Syntax of a JavaScript String Compare

The basic syntax of the JavaScript String Compare function is as shown below:

String_Object1.localcompare(String_Object2, locales)
  • String_Object1: Please specify the valid string to perform a comparison.
  • String_Object2: This argument will compare against the String_Object1
  • Locales: This argument is optional. Here, you can specify one or an array of languages or local tag. LocaleCompare method will consider this argument while comparing String_Object1 and String_Object1.

JavaScript String Compare Example

The following set of examples will help you understand the LocaleCompare() function in JavaScript Programming Language.

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript String Compare </title>
</head>
<body>
    <h1> JavaScript String Comparison </h1>
<script>
    var Str1 = "abc";
    var Str2 = "def";
    var Str3 = "ghi";
    
    var Str4 = Str1.localeCompare(Str2);
    var Str5 = Str3.localeCompare(Str2);
    var Str6 = Str1.localeCompare("abc");
  
    document.write(Str4 + "<br \>");
    document.write(Str5 + "<br \>");
    document.write(Str6 + "<br \>");
</script>
</body>
</html>
JavaScript String Compare

The following statement will compare the substring ‘abc’ with ‘def’ and return the output. As we all know, ‘abc’ will come before the ‘def’ while sorting the data that’s why localeCompare method is returning -1 (Negative one)

var Str4 = Str1.localeCompare(Str2);

Compare the substring ‘ghi’ with ‘def’ and return the output. As we know, ‘ghi’ will come after the ‘def’ while sorting the data that’s why JavaScript localeCompare method is returning 1 (Positive one)

var Str5 = Str3.localeCompare(Str2);

Following JavaScript statement will compare the substring ‘abc’ with ‘abc’ and return the output. As we all know, ‘abc’ is equal to ‘abc’ that’s why localeCompare method is returning 0 (Zero)

var Str6 = Str1.localeCompare("abc");