如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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'
当前回答
正则表达式(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(计数);
其他回答
没有人会看到这一点,但偶尔带回递归和箭头函数是很好的(双关语的意思很好)
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;
}
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字符串中出现的子字符串,以了解分步说明。
现在这是我遇到的一个非常古老的线索,但随着许多人推送他们的答案,这里是我的,希望能帮助一些人使用这个简单的代码。
var search_value=“这是一个假句子!”;var letter='a'/*可以接受任何字母,如果任何人想动态使用此变量,请输入一个var*/letter=letter&&“string”===字母类型?字母:“”;变量计数;对于(var i=count=0;i<search_value.length;count+=(search_value[i++]==字母));console.log(计数);
我不确定它是否是最快的解决方案,但我更喜欢它,因为它简单且不使用正则表达式(我只是不喜欢使用它们!)
String.prototype.Count=函数(查找){返回this.split(find).length-1;}console.log(“这是一个字符串。”.Count(“是”));
这将返回2。