Count Total Amount Of Specific Word In a String JavaScript

做~自己de王妃 提交于 2021-02-15 07:43:34

问题


I want to find out how many time a specific words occur in a String JavaScript, or we can say the total amount of matched/match word with the complete sentence string in JavaScript.

query = "fake";

var inputString = "fakefakefakegg fake 00f0 221 Hello wo fake misinfo fakeddfakefake , wo misinfo misinfo co wo fake , fake fake fake ";

expected result = 13 (there is 13 fake in the above sentence)


回答1:


Here are two methods to find the total number of occurrence match words in the string.

The first function allows you to give a query as input. The second one uses the .match function of JavaScript.

Both introduced methods are resistant for any chars and independent of splitter and separator like " " or ",".

str1 is your query

 str1 = "fake";  

str2 is the whole string:

 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 ";

Method 1 : use .indexOf or .search function of JavaScript (advantage you can give input)

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;
   }

Method 2 : use .match function of JavaScript:

/**
 * @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;
}

call the functions (Inputs):

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


来源:https://stackoverflow.com/questions/65036247/count-total-amount-of-specific-word-in-a-string-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!