文字列JavaScript内の特定の単語の合計量をカウントする

Nov 27 2020

文字列JavaScriptで特定の単語が何回出現するかを知りたい、またはJavaScriptで完全な文の文字列と一致/一致する単語の合計量を言うことができます。

query = "fake";

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

期待される結果= 13(上記の文には13の偽物があります)

回答

FarbodAprin Nov 27 2020 at 11:02

文字列内の一致する単語の合計数を見つける2つの方法を次に示します。

最初の関数を使用すると、クエリを入力として指定できます。2つ目は、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 ";

方法1: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;
   }

方法2: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