查找两个字符串之间的共享元素-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
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西