如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
当前回答
你可以试试这个
let count = s.length - s.replace(/is/g, "").length;
其他回答
只需编码打高尔夫球丽贝卡·切尔诺夫的解决方案:-)
alert(("This is a string.".match(/is/g) || []).length);
试试看:
function countString(str, search){
var count=0;
var index=str.indexOf(search);
while(index!=-1){
count++;
index=str.indexOf(search,index+1);
}
return count;
}
太老了,但我今天需要做这样的事情,只想事后检查一下。对我来说工作很快。
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;
};
const getLetterMatchCount = (guessedWord, secretWord) => {
const secretLetters = secretWord.split('');
const guessedLetterSet = new Set(guessedWord);
return secretLetters.filter(letter => guessedLetterSet.has(letter)).length;
};
const str = "rahul";
const str1 = "rajendra";
getLetterMatchCount(str, str1)
这是我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(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性