 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 characters and prepare a new string of those characters.
Lastly, the function should return that string.
The code for this will be −
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
And the output in the console will be −
[ 'l', 'lo', 'lov', 'love', 'o', 'ov', 'ove', 'v', 've', 'e' ]
Advertisements
 