Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Differences in two strings in JavaScript
We are required to write a JavaScript function that takes in two strings and find the number of corresponding dissimilarities in the strings. The corresponding elements will be dissimilar if they are not equal at the same position.
Example Strings
Let's say the following are our strings:
const str1 = 'Hello world!!!'; const str2 = 'Hellp world111';
In this case, we need to compare each character at the same index and count how many positions have different characters.
Method 1: Using a For Loop
const str1 = 'Hello world!!!';
const str2 = 'Hellp world111';
const dissimilarity = (str1 = '', str2 = '') => {
let count = 0;
const maxLength = Math.max(str1.length, str2.length);
for(let i = 0; i
4
Differences at positions:
Position 4: 'o' vs 'p'
Position 11: '!' vs '1'
Position 12: '!' vs '1'
Position 13: '!' vs '1'
Method 2: Using Array Methods
const str1 = 'Hello world!!!';
const str2 = 'Hellp world111';
const dissimilarityWithArray = (str1, str2) => {
const maxLength = Math.max(str1.length, str2.length);
return Array.from({length: maxLength}, (_, i) => str1[i] !== str2[i])
.filter(Boolean).length;
};
console.log(dissimilarityWithArray(str1, str2));
4
Handling Edge Cases
const dissimilarityRobust = (str1 = '', str2 = '') => {
if (typeof str1 !== 'string' || typeof str2 !== 'string') {
throw new Error('Both inputs must be strings');
}
let count = 0;
const maxLength = Math.max(str1.length, str2.length);
for(let i = 0; i
2
4
0
Comparison Table
| Method | Readability | Performance | Handles Different Lengths |
|---|---|---|---|
| For Loop | High | Fast | Yes |
| Array Methods | Medium | Slower | Yes |
Conclusion
The for loop approach is the most efficient way to count character differences between two strings. Always handle different string lengths by using the maximum length to ensure all positions are compared.
Advertisements
