如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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'
当前回答
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
其他回答
你可以试试这个:
var theString=“这是一个字符串。”;console.log(String.split(“is”).length-1);
var myString = "This is a string.";
var foundAtPosition = 0;
var Count = 0;
while (foundAtPosition != -1)
{
foundAtPosition = myString.indexOf("is",foundAtPosition);
if (foundAtPosition != -1)
{
Count++;
foundAtPosition++;
}
}
document.write("There are " + Count + " occurrences of the word IS");
请参阅:-count字符串中出现的子字符串,以了解分步说明。
我们可以使用jssplit函数,它的长度减1就是出现的次数。
var temp = "This is a string.";
alert(temp.split('is').length-1);
var temp=“这是一个字符串。”;console.log((temp.match(新RegExp(“is”,“g”))||[]).length);
一种简单的方法是将字符串拆分为所需单词,即我们要计算出现次数的单词,然后从部分数中减去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