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

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

当前回答

没有人会看到这一点,但偶尔带回递归和箭头函数是很好的(双关语的意思很好)

String.prototype.occurrencesOf = function(s, i) {
 return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};

其他回答

试试看:

function countString(str, search){
    var count=0;
    var index=str.indexOf(search);
    while(index!=-1){
        count++;
        index=str.indexOf(search,index+1);
    }
    return count;
}

基于@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;
}

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

正则表达式(global的缩写)中的g表示搜索整个字符串,而不仅仅是查找第一个出现的字符串。此匹配是两次:

var temp=“这是一个字符串。”;var count=(temp.match(/is/g)| |[]).length;console.log(计数);

如果没有匹配项,则返回0:

var temp=“Hello World!”;var count=(temp.match(/is/g)| |[]).length;console.log(计数);

对于将来找到此线程的任何人,请注意,如果您对其进行概括,则接受的答案不会总是返回正确的值,因为它会阻塞正则表达式运算符,如$和。。这里有一个更好的版本,可以处理任何针头:

function occurrences (haystack, needle) {
  var _needle = needle
    .replace(/\[/g, '\\[')
    .replace(/\]/g, '\\]')
  return (
    haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
  ).length
}
var mystring = 'This is the lorel ipsum text';
var mycharArray = mystring.split('');
var opArr = [];
for(let i=0;i<mycharArray.length;i++){
if(mycharArray[i]=='i'){//match the character you want to match
    opArr.push(i);
  }}
console.log(opArr); // it will return matching index position
console.log(opArr.length); // it will return length