如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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(计数);
其他回答
正则表达式(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)));
};
你可以试试这个:
var theString=“这是一个字符串。”;console.log(String.split(“is”).length-1);
太老了,但我今天需要做这样的事情,只想事后检查一下。对我来说工作很快。
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;
};
非正则表达式版本:
var string='这是一个字符串',searchFor='is',计数=0,pos=string.indexOf(searchFor);而(位置>-1){++计数;pos=string.indexOf(searchFor,++pos);}console.log(计数);//2.