如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:

var temp = "This is a string.";
alert(temp.count("is")); //should output '2'

当前回答

Leandro Batista的答案:只是正则表达式有问题。

“使用严格”;var dataFromDB=“testal”;$('input[name=“tbInput”]').on(“change”,function(){var charToTest=$(this).val();var howManyChars=charToTest.length;var nrMatches=0;如果(howManyChars!==0){charToTest=charToTest.charAt(0);var regexp=新regexp(charToTest,'gi');var arrMatches=dataFromDB.match(正则表达式);nrMatches=arrMatches?arrMatches.length:0;}$('#result').html(nrMatches.toString());});<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div class=“main”>你想数什么<input type=“text”name=“tbInput”value=“”><br/>出现次数=<span id=“result”>0</span></div>

其他回答

这是我的解决方案。我希望这会对某人有所帮助

const countOccurence = (string, char) => {
const chars = string.match(new RegExp(char, 'g')).length
return chars;
}

var countInstances=函数(主体,目标){var全局计数器=0;var concatstring=“”;for(var i=0,j=target.length;i<body.length;i++){concatstring=body.substring(i-1,j);if(concatstring===目标){全局计数器+=1;concatstring='';}}返回全局计数器;};console.log(countInstance('abcabc','abc'));//==>2.console.log(countInstance('ababa','aba'));//==>2.console.log(countInstance('aaabbb','ab'));//==>1.

无正则表达式的简单版本:

var temp=“这是一个字符串。”;var计数=(临时拆分('is').长度-1);警报(计数);

var temp=“这是一个字符串。”;console.log((temp.match(新RegExp(“is”,“g”))||[]).length);

基于@Vittim.us的上述回答。我喜欢他的方法给我的控制,使其易于扩展,但我需要添加不区分大小写的功能,并将匹配限制在支持标点符号的整个单词中。(例如,“洗澡”是指“洗澡”,而不是“洗澡”)

标点正则表达式来自:https://stackoverflow.com/a/25575009/497745(如何使用正则表达式从JavaScript字符串中删除所有标点符号?)

function keywordOccurrences(string, subString, allowOverlapping, caseInsensitive, wholeWord)
{

    string += "";
    subString += "";
    if (subString.length <= 0) return (string.length + 1); //deal with empty strings

    if(caseInsensitive)
    {            
        string = string.toLowerCase();
        subString = subString.toLowerCase();
    }

    var n = 0,
        pos = 0,
        step = allowOverlapping ? 1 : subString.length,
        stringLength = string.length,
        subStringLength = subString.length;

    while (true)
    {
        pos = string.indexOf(subString, pos);
        if (pos >= 0)
        {
            var matchPos = pos;
            pos += step; //slide forward the position pointer no matter what

            if(wholeWord) //only whole word matches are desired
            {
                if(matchPos > 0) //if the string is not at the very beginning we need to check if the previous character is whitespace
                {                        
                    if(!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchPos - 1])) //ignore punctuation
                    {
                        continue; //then this is not a match
                    }
                }

                var matchEnd = matchPos + subStringLength;
                if(matchEnd < stringLength - 1)
                {                        
                    if (!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchEnd])) //ignore punctuation
                    {
                        continue; //then this is not a match
                    }
                }
            }

            ++n;                
        } else break;
    }
    return n;
}

如果发现错误或改进,请随时修改和重构此答案。