在兩個字串中查詢共享元素 - 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP