如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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 str=“堆栈流”;var arr=Array.from(str);控制台日志(arr);for(设a=0;a<=arr.length;a++){变量温度=arr[a];变量c=0;for(设b=0;b<=arr.length;b++){如果(温度==arr[b]){c++;}}console.log(“${arr[a]}计入${c}”)}
其他回答
String.prototype.Count=函数(查找){返回this.split(find).length-1;}console.log(“这是一个字符串。”.Count(“是”));
这将返回2。
我们可以使用jssplit函数,它的长度减1就是出现的次数。
var temp = "This is a string.";
alert(temp.split('is').length-1);
这是我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(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性
函数countInstance(字符串,单词){返回字符串.split(word).length-1;}console.log(countInstance(“This is a string”,“is”))
非正则表达式版本:
var string='这是一个字符串',searchFor='is',计数=0,pos=string.indexOf(searchFor);而(位置>-1){++计数;pos=string.indexOf(searchFor,++pos);}console.log(计数);//2.