这里有两种方法来查找字符串中出现匹配词的总数。
第一个函数允许您将查询作为输入。
第二个使用了JavaScript的.match函数。
这两种引入的方法都可以抵抗任何字符,并且独立于分隔符和分隔符,如“”或“,”。
str1 是您的查询
str1 = "fake";
str2 是整个字符串:
var inputString = "fakefakefakegg fake 00f0 221 Hello wo fake misinfo
fakeddfakefake , wo 431,,asd misinfo misinfo co wo fake sosis bandari
mikhori?, fake fake fake ";
方法一:使用 JavaScript 的 .indexOf 或 .search 函数(优点是可以输入)
function CountTotalAmountOfSpecificWordInaString(str1, str2)
{
let next = 0;
let findedword = 0;
do {
var n = str2.indexOf(str1, next);
findedword = findedword +1;
next = n + str1.length;
}while (n>=0);
console.log("total finded word :" , findedword - 1 );
return findedword;
}
方法二:使用JavaScript的.match函数:
/**
* @return {number}
* you have to put fake as query manually in this solution!!! disadvantage
*/
function CountTotalAmountOfMachedWordInaString(str2) {
let machedWord = 0;
machedWord = str2.match(/fake/g).length;
console.log("total finded mached :" , machedWord);
return machedWord;
}
调用函数(输入):
CountTotalAmountOfSpecificWordInaString("fake" , "fake fakefakegg fake 00f0 221 Hello wo fake rld fakefakefake , wo lklsak dalkkfakelasd co wo fake , fake fake fake" );
CountTotalAmountOfMachedWordInaString("sosis bandarie fake khiyarshour sosis , droud bar fake to sosis3");
//Function 1 Output: total Fake = 13 , Function 2 Output: total Fake = 2