【问题标题】:Count Total Amount Of Specific Word In a String JavaScript计算字符串 JavaScript 中特定单词的总数
【发布时间】:2021-03-10 04:07:48
【问题描述】:

我想知道一个特定单词在 JavaScript 字符串中出现了多少次,或者我们可以用 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(上句有13个假)

【问题讨论】:

    标签: javascript string search match find-occurrences


    【解决方案1】:

    这里有两种方法来查找字符串中出现匹配词的总数。

    第一个函数允许您将查询作为输入。 第二个使用了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
    

    【讨论】:

    • 可以将 /var/g 放入变量中,str2.match( /var/g )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2011-09-26
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多