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
Function to check two strings and return common words in JavaScript
We are required to write a JavaScript function that takes in two strings as arguments. The function should then check the two strings for common substrings and prepare an array of those common parts.
The function will find all possible substrings from the first string and check if they exist in the second string, returning an array of matches.
Example
const str1 = "IloveLinux";
const str2 = "weloveNodejs";
const findCommon = (str1 = '', str2 = '') => {
const common = Object.create(null);
let i, j, part;
for (i = 0; i < str1.length - 1; i++) {
for (j = i + 1; j <= str1.length; j++) {
part = str1.slice(i, j);
if (str2.indexOf(part) !== -1) {
common[part] = true;
}
}
}
const commonEl = Object.keys(common);
return commonEl;
};
console.log(findCommon(str1, str2));
Output
[
'l', 'lo', 'lov',
'love', 'o', 'ov',
'ove', 'v', 've',
'e'
]
How It Works
The function uses nested loops to generate all possible substrings from the first string. For each substring, it checks if it exists in the second string using indexOf(). Found substrings are stored as keys in an object to avoid duplicates, then converted to an array using Object.keys().
Alternative Approach: Finding Individual Characters Only
If you only need common individual characters (not substrings), here's a simpler approach:
const findCommonChars = (str1, str2) => {
const common = new Set();
for (let char of str1) {
if (str2.includes(char)) {
common.add(char);
}
}
return Array.from(common);
};
console.log(findCommonChars("IloveLinux", "weloveNodejs"));
[ 'l', 'o', 'v', 'e' ]
Conclusion
The first approach finds all common substrings between two strings, while the second finds only common individual characters. Choose based on whether you need substring matching or just character overlap detection.
