Open In App

Optimum way to compare strings in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will know the optimal way to compare the strings using built-in JavaScript methods & will see their implementation through the examples. The question is to compare 2 JavaScript strings optimally. To do so, here are a few of the most used techniques discussed. The method discussed below is used in the following examples. 

String localeCompare() Method: This method compares two strings in the current locale. The current locale is based on the language settings of the browser. This method returns a number that tells whether the string comes before, after, or is equal to the compareString in sort order.

Syntax:

string.localeCompare(String_2);

Parameters:

  • String_2: This required parameter specifies the string to be compared with.

Please refer to the JavaScript Operators Complete Reference article for further details on operators.

Example 1: This example compares the 2 strings using localeCompare() method and returns 0, -1, or 1. This method does case-sensitive comparisons.

Javascript




let str1 = "GFG"
let str2 = "GeeksforGeeks"
 
let ans = str1.localeCompare(str2);
let res = "";
 
if (ans == -1) {
    res = '"' + str1 + '" comes before "' + str2 + '"';
} else if (ans === 0) {
    res = 'Both string are same';
} else {
    res = '"' + str1 + '" comes after "' + str2 + '"';
}
 
console.log(res);


Output

"GFG" comes after "GeeksforGeeks"

Example 2: This example compares the 2 strings by writing a condition that returns 0, -1, or 1 depending on the comparison. This method also does case-sensitive comparisons.

Javascript




let str1 = "Geeks"
let str2 = "GFG"
 
let ans = str1 < str2 ? -1 : (str1 > str2 ? 1 : 0);
let res = "";
 
if (ans == -1) {
    res = '"' + str1 + '" comes before "' + str2 + '"';
} else if (ans === 0) {
    res = 'Both string are same';
} else {
    res = '"' + str1 + '" comes after "' + str2 + '"';
}
 
console.log(res);


Output

"Geeks" comes after "GFG"

Example 3: This example compares the 2 same strings (case-sensitive also) by using the localeCompare() method.

Javascript




let str1 = "GeeksforGeeks"
let str2 = "GeeksforGeeks"
 
let ans = str1.localeCompare(str2);
let res = "";
 
if (ans == -1) {
    res = '"' + str1 + '" comes before "' + str2 + '"';
} else if (ans == 0) {
    res = 'Both string are same';
} else {
    res = '"' + str1 + '" comes after "' + str2 + '"';
}
 
console.log(res);


Output

Both string are same


Last Updated : 07 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads