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
Finding shared element between two strings - JavaScript
We are required to write a JavaScript function that takes in two strings that may / may not contain some common elements. The function should return an empty string if no common element exists otherwise a string containing all common elements between two strings.
Following are our two strings ?
const str1 = 'Hey There!!, how are you'; const str2 = 'Can this be a special string';
Example
Following is the code ?
const str1 = 'Hey There!!, how are you';
const str2 = 'Can this be a special string';
const commonString = (str1, str2) => {
let res = '';
for(let i = 0; i < str1.length; i++){
if(!str2.includes(str1[i])){
continue;
};
res += str1[i];
};
return res;
};
console.log(commonString(str1, str2));
Output
Following is the output in the console ?
e here h are
How It Works
The function iterates through each character of the first string and checks if that character exists in the second string using the includes() method. If a character is found in both strings, it gets added to the result string. This approach preserves the order of characters as they appear in the first string.
Alternative Approach Using Set
Here's another method that removes duplicate characters from the result:
const str1 = 'Hey There!!, how are you';
const str2 = 'Can this be a special string';
const commonStringUnique = (str1, str2) => {
let res = '';
const seen = new Set();
for(let char of str1) {
if(str2.includes(char) && !seen.has(char)) {
res += char;
seen.add(char);
}
}
return res;
};
console.log(commonStringUnique(str1, str2));
e her a
Conclusion
Both methods effectively find common characters between two strings. The first approach preserves duplicates and maintains character order, while the Set-based approach returns only unique common characters.
