如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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'
当前回答
一种简单的方法是将字符串拆分为所需单词,即我们要计算出现次数的单词,然后从部分数中减去1:
function checkOccurences(string, word) {
return string.split(word).length - 1;
}
const text="Let us see. see above, see below, see forward, see backward, see left, see right until we will be right";
const count=countOccurences(text,"see "); // 2
其他回答
太老了,但我今天需要做这样的事情,只想事后检查一下。对我来说工作很快。
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;
};
正则表达式(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(计数);
看到这篇帖子。
let str = 'As sly as a fox, as strong as an ox';
let target = 'as'; // let's look for it
let pos = 0;
while (true) {
let foundPos = str.indexOf(target, pos);
if (foundPos == -1) break;
alert( `Found at ${foundPos}` );
pos = foundPos + 1; // continue the search from the next position
}
相同的算法可以被布置得更短:
let str = "As sly as a fox, as strong as an ox";
let target = "as";
let pos = -1;
while ((pos = str.indexOf(target, pos + 1)) != -1) {
alert( pos );
}
试试看
<?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>
我认为regex的目的与indexOf有很大不同。indexOf只需查找某个字符串的出现,而在正则表达式中,您可以使用[a-Z]之类的通配符,这意味着它将查找单词中的任何大写字符,而无需说明实际字符。
例子:
var index=“This is a string”.indexOf(“is”);console.log(索引);var length=“This is a string”.match(/[a-z]/g).length;//其中[a-z]是正则表达式通配符,这就是为什么其速度较慢的原因console.log(长度);