如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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'
当前回答
添加了此优化:
如何计算字符串中的字符串出现次数?
这可能是这里最快的实现,但如果您将“++pos”替换为“pos+=searchFor.length”,则会更快汉森里克
function occurrences(str_, subStr) {
let occurence_count = 0
let pos = -subStr.length
while ((pos = str_.indexOf(subStr, pos + subStr.length)) > -1) {
occurence_count++
}
return occurence_count
}
其他回答
我的解决方案:
var temp=“这是一个字符串。”;函数countOccurrences(str,value){var regExp=新regExp(值,“gi”);return(str.match(regExp)| |[]).length;}console.log(countOccurrences(temp,'is'));
试试看
<?php
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>
<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);
alert(count.length);
</script>
这是我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(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性
正则表达式(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(计数);
你可以试试这个:
var theString=“这是一个字符串。”;console.log(String.split(“is”).length-1);