如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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'
当前回答
函数countInstance(字符串,单词){返回字符串.split(word).length-1;}console.log(countInstance(“This is a string”,“is”))
其他回答
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)
String.prototype.Count=函数(查找){返回this.split(find).length-1;}console.log(“这是一个字符串。”.Count(“是”));
这将返回2。
一种简单的方法是将字符串拆分为所需单词,即我们要计算出现次数的单词,然后从部分数中减去1:
function checkOccurences(string, word) {
return string.split(word).length - 1;
}
const text="Let us see. see above, see below, see forward, see backward, see left, see right until we will be right";
const count=countOccurences(text,"see "); // 2
//Try this code
const countSubStr = (str, search) => {
let arrStr = str.split('');
let i = 0, count = 0;
while(i < arrStr.length){
let subStr = i + search.length + 1 <= arrStr.length ?
arrStr.slice(i, i+search.length).join('') :
arrStr.slice(i).join('');
if(subStr === search){
count++;
arrStr.splice(i, search.length);
}else{
i++;
}
}
return count;
}
函数countInstance(字符串,单词){返回字符串.split(word).length-1;}console.log(countInstance(“This is a string”,“is”))