我该如何在一个字符串中统计另一个特定字符串出现的次数?例如,我想在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 temp = "This is a string.";
console.log((temp.match(new RegExp("is", "g")) || []).length);
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
indexOf
大不相同。
indexOf
仅查找特定字符串的出现,而在正则表达式中,您可以使用通配符,如[A-Z]
,它表示将查找单词中的任何大写字符,而无需指定实际字符。 var index = "This is a string".indexOf("is");
console.log(index);
var length = "This is a string".match(/[a-z]/g).length;
// where [a-z] is a regex wildcard expression thats why its slower
console.log(length);
split
函数,它的长度减1将是出现次数。var temp = "This is a string.";
alert(temp.split('is').length-1);
虽然这篇文章有些过时了,但我今天也需要类似的东西,只是在查阅Stack Overflow之后才想起来。对我来说运行相当快。
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 myString = "This is a string.";
var foundAtPosition = 0;
var Count = 0;
while (foundAtPosition != -1)
{
foundAtPosition = myString.indexOf("is",foundAtPosition);
if (foundAtPosition != -1)
{
Count++;
foundAtPosition++;
}
}
document.write("There are " + Count + " occurrences of the word IS");
参考: 计算字符串中子字符串出现的次数,以获得逐步解释。
function keywordOccurrences(string, subString, allowOverlapping, caseInsensitive, wholeWord)
{
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1); //deal with empty strings
if(caseInsensitive)
{
string = string.toLowerCase();
subString = subString.toLowerCase();
}
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length,
stringLength = string.length,
subStringLength = subString.length;
while (true)
{
pos = string.indexOf(subString, pos);
if (pos >= 0)
{
var matchPos = pos;
pos += step; //slide forward the position pointer no matter what
if(wholeWord) //only whole word matches are desired
{
if(matchPos > 0) //if the string is not at the very beginning we need to check if the previous character is whitespace
{
if(!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchPos - 1])) //ignore punctuation
{
continue; //then this is not a match
}
}
var matchEnd = matchPos + subStringLength;
if(matchEnd < stringLength - 1)
{
if (!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?@\[\]^_`{|}~]/.test(string[matchEnd])) //ignore punctuation
{
continue; //then this is not a match
}
}
}
++n;
} else break;
}
return n;
}
如果您发现错误或改进的地方,请随意修改和重构此答案。
对于将来发现这个主题的任何人,请注意,接受的答案如果泛化,不总是会返回正确的值,因为它会被正则表达式操作符 $
和 .
扼杀。以下是更好的版本,可以处理 任何 针:
function occurrences (haystack, needle) {
var _needle = needle
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
return (
haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
).length
}
试一试
<?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>
不使用正则表达式的简单版本:
var temp = "This is a string.";
var count = (temp.split('is').length - 1);
alert(count);