有没有一个函数可以用来检查两个string,并在nodejs中返回常用的单词/字母表

对于Eq:

var str1="IloveLinux"; var str2="weloveNodejs"; 

任何可以返回true / value /或任何可能的标志的函数?

那么你的string只有一个字! 在这种情况下,你只需要检查两个string之间的匹配字符。

解:

这是你需要用来获得匹配元素的function:

 var matchingElements = arr1.filter(function(item) { return arr2.indexOf(item) > -1; }); 

您需要使用string.split("")将string转换为字符数组,然后遍历这两个数组以查找匹配项。

演示

 var str1 = "IloveLinux"; var str2 = "weloveNodejs"; var arr1 = str1.split(""); var arr2 = str2.split(""); var matchingElements = arr1.filter(function(item) { return arr2.indexOf(item) > -1; }); console.log(matchingElements); 

string是可迭代的,所以你不需要将它们转换成数组来迭代它们。 如果你想支持旧浏览器,你可以使用ES6 for...of循环, for...in循环,甚至如果你想支持真正的老浏览器,甚至只是一个基本for(;;){}循环。

如果要返回两个string中存在的所有元素(不是唯一的)的数组,请将所有匹配元素推送到数组上,然后返回该数组。

 const check = (a, b) => { const common = [] for(let l of a) if(b.indexOf(l) >= 0) common.push(l) return common } console.log(check("IloveLinux", "weloveNodejs")) // ['l','o','v','e'] console.log(check("lllll", "lllll")) // ['l','l','l','l','l'] console.log(check("I love Linux".split(' '), "we love Nodejs".split(' '))) // ['love'] 

您可以检查每个子string,并检查第二个string,并以子string为关键字计算对象中的出现次数。

 var str1 = "IloveLinux", str2 = "weloveNodejs", common = Object.create(null), 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; } } } console.log(Object.keys(common)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; }