如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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 search_value=“这是一个假句子!”;var letter='a'/*可以接受任何字母,如果任何人想动态使用此变量,请输入一个var*/letter=letter&&“string”===字母类型?字母:“”;变量计数;对于(var i=count=0;i<search_value.length;count+=(search_value[i++]==字母));console.log(计数);
我不确定它是否是最快的解决方案,但我更喜欢它,因为它简单且不使用正则表达式(我只是不喜欢使用它们!)
其他回答
非正则表达式版本:
var string='这是一个字符串',searchFor='is',计数=0,pos=string.indexOf(searchFor);而(位置>-1){++计数;pos=string.indexOf(searchFor,++pos);}console.log(计数);//2.
正则表达式(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 search_value=“这是一个假句子!”;var letter='a'/*可以接受任何字母,如果任何人想动态使用此变量,请输入一个var*/letter=letter&&“string”===字母类型?字母:“”;变量计数;对于(var i=count=0;i<search_value.length;count+=(search_value[i++]==字母));console.log(计数);
我不确定它是否是最快的解决方案,但我更喜欢它,因为它简单且不使用正则表达式(我只是不喜欢使用它们!)
ES2020提供了一个新的MatchAll,它可能在这个特定的环境中使用。
这里我们创建了一个新的RegExp,请确保将“g”传递到函数中。
使用Array.from转换结果并计算长度,根据原始请求者所需的输出返回2。
let strToCheck=RegExp('is','g')let matchesReg=“这是一个字符串。”.matchAll(strToCheck)console.log(Array.from(matchesReg).length)//2
基于@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;
}
如果发现错误或改进,请随时修改和重构此答案。