我们需要编写一个JavaScript函数,该函数接受两个字符串作为参数。然后,该函数应检查两个字符串中的常见字符并准备一个包含这些字符的新字符串。
最后,该函数应返回该字符串。
为此的代码将是-
const str1 = "IloveLinux";
const str2 = "weloveNodejs";
const findCommon = (str1 = '', str2 = '') => {
const common = Object.create(null);
let i, j, part;
for (i = 0; i < str1.length - 1; i++) {
for (j = i + 1; j <= str1.length; j++) {
part = str1.slice(i, j);
if (str2.indexOf(part) !== −1) {
common[part] = true;
}
}
}
const commonEl = Object.keys(common);
return commonEl;
};
console.log(findCommon(str1, str2));输出结果
控制台中的输出将是-
[ 'l', 'lo', 'lov', 'love', 'o', 'ov', 'ove', 'v', 've', 'e' ]