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'
]

Updated on: 20-Nov-2020

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements