在兩個字串中查詢共享元素 - 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.