Table of Contents
If you want to compare two strings in JavaScript, you have to consider four things also. These are the datatypes of operands, case sensitivity, culture, and strictness. Comparing all factors, here in this article we are going to explore all four popular methods to compare two strings in JavaScript.
JavaScript string comparison is case-sensitive. JS uses Unicode values to compare characters. Usually, JavaScript === and !== operators are used for equality checks, and <, >, <=, >= for ordering comparisons. These comparisons are fundamental for controlling the flow of your program, handling data, and providing interactive and dynamic user experiences.
So, bear with us and read to the end to learn much better than others on everything about JavaScript string comparison.
Why JavaScript String Comparison is too Important?
JavaScript string comparisons are very important for many reasons. From functionality to the behavior of your web application, we can’t make any progress without comparing data. Here are the following key points on why string comparisons are required:
- Conditional Logic: During decision-making time, string comparison plays a vital role in logic development. For example, if we want to check user input with a specific value, such as a menu item, category, or specific command, then string comparison is a must.
- Sorting and Ordering: If you need to sort an array of strings, we can easily determine the order of the strings by comparing them with each other.
- Searching and Filtering: String comparisons are widely used to search and filter data. Searching for a specific substring within a string or filtering an array of strings based on a condition are the two most common examples for JavaScript developers.
- Validation and Verification: If we need to match certain patterns or values, then string comparisons are obvious. It could be an email address, phone number, or other formatted data validation.
- Localization and Internationalization: When working with applications that support multiple languages, string comparisons help manage and display the correct content based on language and locale settings.
- User Interface and Interaction: Many user interfaces rely on just string comparisons, such as determining the state of a button based on their label data or displaying different information based on a different list view option.
Compare Strings Using JS Strict Equality Operator (===)
How do I use the JS strict equality operator (===)? Use the strict equality operator (===) to directly compare two strings for content matching, along with the case sensitivity and their data type, without type coercion. This is the most straightforward and recommended method for string equality checks in JavaScript.
Code Example: Compare Two Strings in JavaScript
<script>
// javascript string comparison
var str1 = 'javascript program';
var str2 = 'javascript program';
var str3 = 'JavaScript program';
// Compare Two Strings in JavaScript
var result1 = str1 === str2;
var result2 = str2 === str3;
if(result1) {
console.log(str1 +' & '+str2+': Strings are same.');
} else {
console.log(str1 +' & '+str2+': Strings are different.');
}
if(result2) {
console.log(str2 +' & '+str3+': Strings are same.');
} else {
console.log(str2 +' & '+str3+': Strings are different.');
}
</script>
Output
Code Explanation
In the above program, we used three variables to compare. Here, all three string variables have the same value, but only the third variable contains some uppercase characters.
The variables result1 and result2 are used to hold the comparison values of var1, var2, and var3, respectively.
The if..else is used to print the result based on the condition.
One important point to notice that, according to the second condition check we found that JS Strict Equality Operator (===) is case sensitive.
Make a Generic Function for JavaScript String Comparison
<script>
// javascript string comparison function
function compareTwoStrings(str1,str2,isCaseSensitive,bTrim)
{
// Using javascript trim() function
// while comparing two strings in JS
if(bTrim)
{
str1=str1.trim();
str2=str2.trim();
}
if(isCaseSensitive)
return str1 === str2;
else
return str1.toUpperCase() === str2.toUpperCase();
}
var str1 = 'javascript program';
var str2 = ' javascript program ';
var str3 = 'JavaScript program ';
// Compare Two Strings in JavaScript
// Change 3rd param value to check case sensitivity
// change fourth parameter to check JS TRIM() function
var result1 = compareTwoStrings(str1,str2,true,true);
var result2 = compareTwoStrings(str2,str3,false,true);
if(result1) {
console.log(str1 +' & '+str2+': Strings are same.');
} else {
console.log(str1 +' & '+str2+': Strings are different.');
}
if(result2) {
console.log(str2 +' & '+str3+': Strings are same.');
} else {
console.log(str2 +' & '+str3+': Strings are different.');
}
</script>
Using JS loose Equality Operator (==)
The JS loose equality operator (==) allows automatic type conversions of operands, which means it supports type coercion. It’s strongly recommended to use the loose equality operator if you are 100% sure about both comparable string data types in your code. If you are not sure about the type before doing the comparison, you must use the strict equality operator (===) instead to avoid the coercion effect.
We all knew that auto-conversions convert blank strings to zero or 1 to true based on other operand types due to coercion.
Code Example: Compare Two Strings in JavaScript
<script>
// javascript string comparison
var str1 = 'javascript program';
var str2 = 'javascript program';
var str3 = 'JavaScript program';
// Compare Two Strings in JavaScript
// by loosely equality operator (==)
var result1 = str1 == str2;
var result2 = str2 == str3;
if(result1) {
console.log(str1 +' & '+str2+': Strings are same.');
} else {
console.log(str1 +' & '+str2+': Strings are different.');
}
// compare string js
if(result2) {
console.log(str2 +' & '+str3+': Strings are same.');
} else {
console.log(str2 +' & '+str3+': Strings are different.');
}
</script>
Here in the above example we found that our both strings str1 and str2 datatype is string. So we can use the loose equality operator (==) to compare two strings in JavaScript safely.
Output
We also see that JS loose equality operator (==) is case sensitive.
Code explanation is not required as we are using the same script to explain the different purposes with slight modifications.
Make a Generic Function to Compare Strings JS
Here we are going to mention the changed part only. The generic function is the same as before. Just change the strict operator (===) to the loose operator (==) within the compareTwoStrings function. Other lines of code and parameters will remain the same.
// Just change (===) to (==)
// Rest others are same
if(isCaseSensitive)
return str1 == str2;
else
return str1.toUpperCase() == str2.toUpperCase();
// compare string js
How is == Different from === in JavaScript?
So far we have already explained a lot about the difference between the strict operator (===) and loose operator (==). But it’s our duty to make you more knowledgeable. Hence we are going to explain a bit more in the following section:
The main difference between the === and == operators in JavaScript is that the === operator compares the values and both operand data types before comparison, whereas the == operator does an automatic type conversion of both operands before the conversion.
Almost every programming language does the same automatic data type conversion before comparing two values. This is called type coercion. In the examples above, we have tried our best to make you understand the concept. I hope we succeeded. If yes, please love us and share our article on your social media platforms.
Let’s understand with More Example
<script>
var operand1 = 99;
var operand2 = '99';
console.log('Using (===) JS Operator: ' + (operand1 === operand2));
// Output >> Using (===) JS Operator: false
console.log('Using (==) JS Operator: ' + (operand1 == operand2));
// output >> Using (==) JS Operator: true
</script>
If you look at the outputs, one returns false, but another returns true. Why? Because the datatypes of both operands are not the same (int and string) for the (===) operator. The (===) operator directly compares two strings for content matching and date type without type coercion.
Based on above example you may think that (==) operator is best. But look at below code example:
<script>
var operand1 = true;
var operand2 = '1';
console.log('Using (===) JS Operator: ' + (operand1 === operand2));
// Output >> Using (===) JS Operator: false
console.log('Using (==) JS Operator: ' + (operand1 == operand2));
// output >> Using (==) JS Operator: true
</script>
Look how how dangerous the loose (==) operator is. That’s why we recommend to use strict (===) operator.
More Example
<script>
var operand1 = 0;
var operand2 = '';
console.log('Using (===) JS Operator: ' + (operand1 === operand2));
// Output >> Using (===) JS Operator: false
console.log('Using (==) JS Operator: ' + (operand1 == operand2));
// output >> Using (==) JS Operator: true
</script>
I hope now everything is cleared and we don’t need to discuss further. If you still have confusion on this Javascript topic, please leave a comment.
Using JavaScript Localecompare Method
Use the JS localeCompare() method if you need to consider region-specific rules in your string equality checks. This method returns 0 when it considers two strings equal, or 1 or -1 in case of a mismatch.
Return Values of the JavaScript Localecompare Method
0 | The alphabetic order of both strings is the same. |
1 | When the first operand’s alphabetic order is greater than the second operand’s alphabetic order. |
-1 | When the second operand’s alphabetic order is greater than the first operand’s alphabetic order. |
<script>
var operand1 = 'a';
var operand2 = 'A';
// using javascript localecompare method
console.log(operand1.localeCompare(operand2));
// Output >> -1
</script>
The JavaScript Localecompare Method returns -1 because capital ‘A’ is greater than small ‘a’ in English alphabet order.
<script>
var operand1 = 'A';
var operand2 = 'a';
// using javascript localecompare method
console.log(operand1.localeCompare(operand2));
// Output >> 1
</script>
The JavaScript Localecompare Method returns 1 because of order change.
<script>
var operand1 = 'A';
var operand2 = 'A';
// using javascript localecompare method
console.log(operand1.localeCompare(operand2));
// Output >> 0
</script>
The JavaScript Localecompare Method returns 0 because the alphabetic order is same.
Make a Generic Function for JavaScript String Comparison
<script>
// javascript string comparison function
function compareTwoStrings(str1,str2,isCaseSensitive,bTrim)
{
// Using javascript trim() function
// while comparing two strings in JS
if(bTrim)
{
str1=str1.trim();
str2=str2.trim();
}
if(isCaseSensitive)
return str1.localeCompare(str2);
else
return str1.toUpperCase().localeCompare(str2.toUpperCase());
}
var str1 = 'javascript program';
var str2 = 'javascript program';
var str3 = 'JavaScript program ';
// Compare Two Strings in JavaScript
// Change 3rd param value to check case sensitivity
// change fourth parameter to check JS TRIM() function
var result1 = compareTwoStrings(str1,str2,true,true);
var result2 = compareTwoStrings(str2,str3,false,true);
// As JavaScript Localecompare Method returns 0 if matched
if(result1==0) {
console.log(str1 +' & '+str2+': Strings are same.');
} else {
console.log(str1 +' & '+str2+': Strings are different.');
}
// As JavaScript Localecompare Method returns 0 if matched
if(result2==0) {
console.log(str2 +' & '+str3+': Strings are same.');
} else {
console.log(str2 +' & '+str3+': Strings are different.');
}
</script>
Output
JavaScript Compare Strings: Using Regular Expression
In Javascript, we can also compare two strings using the regular expressions test method. Here is the example:
<script>
// javascript string comparison
var str1 = 'javascript program';
var str2 = 'JavaScript program';
// make the regex expression
var regPattern1 = new RegExp(str1, "g");
var regPattern2 = new RegExp(str1, "gi");
// compare the stings
var result1 = regPattern1.test(str2);
var result2 = regPattern2.test(str2);
if(result1) {
console.log(str1 +' & '+str2+': Strings are same.');
} else {
console.log(str1 +' & '+str2+': Strings are different.');
}
if(result2) {
console.log(str1 +' & '+str2+': Strings are same.');
} else {
console.log(str1 +' & '+str2+': Strings are different.');
}
</script>
Output
Conclusion
So, we have discussed four powerful ways to compare two strings in JavaScript. At first, we discuss the JS strict equality operator (===) and then the loose equality operator (==). We have also mentioned the difference between the JS strict equality operator and the loose operator.
We have also outlined a generic method for both JS equality operators so that you can experiment as per your needs. We discussed a lot of aspects about case sensitivity and the JS trim function as well.
Later on, we discussed the JavaScript Localecompare Method with all of its return types, and at the end, we also discussed how we can compare two strings in JavaScript using a regular expression. I hope you enjoyed it a lot!!
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply