如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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=“这是一个字符串。”;var计数=(临时拆分('is').长度-1);警报(计数);
其他回答
没有人会看到这一点,但偶尔带回递归和箭头函数是很好的(双关语的意思很好)
String.prototype.occurrencesOf = function(s, i) {
return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};
第二次迭代次数较少(仅当子字符串的第一个字母匹配时),但循环仍使用2:
function findSubstringOccurrences(str, word) {
let occurrences = 0;
for(let i=0; i<str.length; i++){
if(word[0] === str[i]){ // to make it faster and iterate less
for(let j=0; j<word.length; j++){
if(str[i+j] !== word[j]) break;
if(j === word.length - 1) occurrences++;
}
}
}
return occurrences;
}
console.log(findSubstringOccurrences("jdlfkfomgkdjfomglo", "omg"));
基于@Vittim.us的上述回答。我喜欢他的方法给我的控制,使其易于扩展,但我需要添加不区分大小写的功能,并将匹配限制在支持标点符号的整个单词中。(例如,“洗澡”是指“洗澡”,而不是“洗澡”)
标点正则表达式来自:https://stackoverflow.com/a/25575009/497745(如何使用正则表达式从JavaScript字符串中删除所有标点符号?)
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
}
//Try this code
const countSubStr = (str, search) => {
let arrStr = str.split('');
let i = 0, count = 0;
while(i < arrStr.length){
let subStr = i + search.length + 1 <= arrStr.length ?
arrStr.slice(i, i+search.length).join('') :
arrStr.slice(i).join('');
if(subStr === search){
count++;
arrStr.splice(i, search.length);
}else{
i++;
}
}
return count;
}