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

Updated on: 18-Sep-2020

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements