JavaScript 中检查两个字符串并返回常用单词的函数
javascriptfront end technologyobject oriented programmingweb development
我们需要编写一个 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' ]