在两个字符串中查找共享元素 - JavaScript


我们需要写一个 JavaScript 函数,该函数输入两个可能包含一些公共元素的字符串。如果不存在公共元素,该函数应返回一个空字符串,否则返回一个包含两个字符串之间所有公共元素的字符串。

以下是我们两个字符串 -

const str1 = 'Hey There!!, how are you';
const str2 = 'Can this be a special string';

示例

以下为代码 -

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));

输出

以下是控制台中的输出 -

e here h are

更新于: 2020年 9 月 18 日

488 次浏览

开始您的 职业生涯

完成课程即可获得认证

开始使用
广告
© . All rights reserved.