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

JavaScript String Compare Syntax

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 check against the String_Object1
  • Locales: This argument is optional. Here, you can specify one or an array of languages or local tag. The JavaScript string compare 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 to do string compare in JavaScript. In this example, we declared three variables using the first three statements

The fourth 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)

Next line differentiate 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)

The last JavaScript statement will check 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)

<!DOCTYPE html>
<html>
<head>
    <title> JavaScriptStringCompare </title>
</head>
<body>
    <h1> JavaScript StringComparison </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