如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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'
当前回答
这是我的解决方案。我希望这会对某人有所帮助
const countOccurence = (string, char) => {
const chars = string.match(new RegExp(char, 'g')).length
return chars;
}
其他回答
这是我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(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性
非正则表达式版本:
var string='这是一个字符串',searchFor='is',计数=0,pos=string.indexOf(searchFor);而(位置>-1){++计数;pos=string.indexOf(searchFor,++pos);}console.log(计数);//2.
ES2020提供了一个新的MatchAll,它可能在这个特定的环境中使用。
这里我们创建了一个新的RegExp,请确保将“g”传递到函数中。
使用Array.from转换结果并计算长度,根据原始请求者所需的输出返回2。
let strToCheck=RegExp('is','g')let matchesReg=“这是一个字符串。”.matchAll(strToCheck)console.log(Array.from(matchesReg).length)//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。