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

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

当前回答

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

function occurrences (haystack, needle) {
  var _needle = needle
    .replace(/\[/g, '\\[')
    .replace(/\]/g, '\\]')
  return (
    haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
  ).length
}

其他回答

看到这篇帖子。

let str = 'As sly as a fox, as strong as an ox';

let target = 'as'; // let's look for it

let pos = 0;
while (true) {
  let foundPos = str.indexOf(target, pos);
  if (foundPos == -1) break;

  alert( `Found at ${foundPos}` );
  pos = foundPos + 1; // continue the search from the next position
}

相同的算法可以被布置得更短:

let str = "As sly as a fox, as strong as an ox";
let target = "as";

let pos = -1;
while ((pos = str.indexOf(target, pos + 1)) != -1) {
  alert( pos );
}

太老了,但我今天需要做这样的事情,只想事后检查一下。对我来说工作很快。

String.prototype.count = function(substr,start,overlap) {
    overlap = overlap || false;
    start = start || 0;

    var count = 0, 
        offset = overlap ? 1 : substr.length;

    while((start = this.indexOf(substr, start) + offset) !== (offset - 1))
        ++count;
    return count;
};

这是我2022年使用map()和filter()的解决方案:

string = "Xanthous: A person with yellow hair. Her hair was very xanthous in colour."       
count = string.split('').map((e,i) => { if(e === 'e') return i;}).filter(Boolean).length

只是为了使用这些功能的乐趣。该示例计算字符串中“e”的数量。

这与使用match()函数相同:

(string.match(/e/g)||[]).length

或者简单地使用split()函数:

string.split('e').length - 1

我认为最好的方法是使用match(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性

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

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

函数countInstance(字符串,单词){返回字符串.split(word).length-1;}console.log(countInstance(“This is a string”,“is”))