如何计算特定字符串在另一个字符串中出现的次数。 例如,这就是我要使用Javascript进行的操作:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
#1楼
尝试这个:
function countString(str, search){
var count=0;
var index=str.indexOf(search);
while(index!=-1){
count++;
index=str.indexOf(search,index+1);
}
return count;
}
#2楼
您可以尝试以下方法:
var theString = "This is a string."; console.log(theString.split("is").length - 1);
#3楼
我认为regex的目的与indexOf
有很大不同。 indexOf
只是查找某个字符串的出现,而在正则表达式中,您可以使用[AZ]
类的通配符,这意味着它将在单词中找到任何大写字符而无需说明实际字符。
例:
var index = "This is a string".indexOf("is"); console.log(index); var length = "This is a string".match(/[az]/g).length; // where [az] is a regex wildcard expression thats why its slower console.log(length);
#4楼
超级骗子,但我今天需要做这样的事情,只想到以后再检查。 对我来说工作很快。
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;
};
#5楼
我的解决方案:
var temp = "This is a string."; function countOcurrences(str, value) { var regExp = new RegExp(value, "gi"); return (str.match(regExp) || []).length; } console.log(countOcurrences(temp, 'is'));
#6楼
这是最快的功能!
为什么会更快?
- 不按字符检查字符(1个例外)
- 使用一会儿并增加1 var(字符数var)与a进行循环以检查长度并增加2 vars(通常是var i和具有char数的var)
- 使用WAY少的var
- 不使用正则表达式!
- 使用(希望)高度优化的功能
所有操作都尽可能地组合在一起,避免了由于多次操作而导致的速度降低
String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
这是一个较慢且更易读的版本:
String.prototype.timesCharExist = function ( chr ) {
var total = 0, last_location = 0, single_char = ( chr + '' )[0];
while( last_location = this.indexOf( single_char, last_location ) + 1 )
{
total = total + 1;
}
return total;
};
由于计数器,较长的var名称和1 var的误用,因此此速度较慢。
要使用它,只需执行以下操作:
'The char "a" only shows up twice'.timesCharExist('a');
编辑:(2013/12/16)
不要与Opera 12.16或更早版本一起使用! 这将比正则表达式解决方案多花将近2.5倍!
在chrome上,此解决方案将需要14ms到20ms的时间才能处理1,000,000个字符。
正则表达式解决方案花费11-14毫秒即可获得相同的数量。
使用一个函数(在String.prototype
之外)大约需要10-13毫秒。
这是使用的代码:
String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
var x=Array(100001).join('1234567890');
console.time('proto');x.timesCharExist('1');console.timeEnd('proto');
console.time('regex');x.match(/1/g).length;console.timeEnd('regex');
var timesCharExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t;};
console.time('func');timesCharExist(x,'1');console.timeEnd('func');
所有解决方案的结果应为100,000!
注意:如果您希望此函数计算的字符数超过1个,请将c=(c+'')[0]
更改为c=c+''
#7楼
试试吧
<?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>
#8楼
非正则表达式版本:
var string = 'This is a string', searchFor = 'is', count = 0, pos = string.indexOf(searchFor); while (pos > -1) { ++count; pos = string.indexOf(searchFor, ++pos); } console.log(count); // 2
#9楼
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");
请参阅:- 计算子字符串出现在字符串中以进行逐步说明。
#10楼
对于将来会发现此线程的任何人,请注意,如果将其归纳,接受的答案将不会总是返回正确的值,因为它会阻塞$
和的正则表达式运算符.
。 这是一个更好的版本,可以处理任何针:
function occurrences (haystack, needle) {
var _needle = needle
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
return (
haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
).length
}
#11楼
var temp = "This is a string."; console.log((temp.match(new RegExp("is", "g")) || []).length);
#12楼
建立在@ Vittim.us上面的答案上。 我喜欢他的方法提供给我的控件,使它易于扩展,但是我需要增加不区分大小写并在支持标点符号的情况下限制整个单词的匹配。 (例如,“洗澡”在“洗澡”中,但不在“洗澡”中)
标点符号正则表达式来自: https : //stackoverflow.com/a/25575009/497745 ( 如何使用regex从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;
}
如果发现错误或改进,请随时修改和重构此答案。
#13楼
现在,这是我遇到的一个非常老的线程,但是由于许多人都提出了自己的答案,这里是我的希望,希望可以帮助使用此简单代码的人。
var search_value = "This is a dummy sentence!"; var letter = 'a'; /*Can take any letter, have put in a var if anyone wants to use this variable dynamically*/ letter = letter && "string" === typeof letter ? letter : ""; var count; for (var i = count = 0; i < search_value.length; count += (search_value[i++] == letter)); console.log(count);
我不确定这是否是最快的解决方案,但为了简单起见并且不使用正则表达式我更喜欢它(我只是不喜欢使用它们!)
#14楼
没有正则表达式的简单版本:
var temp = "This is a string."; var count = (temp.split('is').length - 1); alert(count);
#15楼
String.prototype.Count = function (find) { return this.split(find).length - 1; } console.log("This is a string.".Count("is"));
这将返回2。
#16楼
正则表达式中的g
(是global的缩写)表示搜索整个字符串,而不是仅查找第一个匹配项。 这场比赛is
两次:
var temp = "This is a string."; var count = (temp.match(/is/g) || []).length; console.log(count);
并且,如果没有匹配项,则返回0
:
var temp = "Hello World!"; var count = (temp.match(/is/g) || []).length; console.log(count);
#17楼
function countInstances(string, word) {
return string.split(word).length - 1;
}
#18楼
您可以使用match
定义此类功能:
String.prototype.count = function(search) {
var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
return m ? m.length:0;
}
#19楼
function get_occurrence(varS,string){//Find All Occurrences c=(string.split(varS).length - 1); return c; } temp="This is a string."; console.log("Total Occurrence is "+get_occurrence("is",temp));
使用get_occurrence(varS,string)查找字符串中字符和字符串的出现。
#20楼
Leandro Batista的答案:正则表达式的问题。
"use strict"; var dataFromDB = "testal"; $('input[name="tbInput"]').on("change",function(){ var charToTest = $(this).val(); var howManyChars = charToTest.length; var nrMatches = 0; if(howManyChars !== 0){ charToTest = charToTest.charAt(0); var regexp = new RegExp(charToTest,'gi'); var arrMatches = dataFromDB.match(regexp); nrMatches = arrMatches ? arrMatches.length : 0; } $('#result').html(nrMatches.toString()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main"> What do you wanna count <input type="text" name="tbInput" value=""><br /> Number of occurences = <span id="result">0</span> </div>
#21楼
var countInstances = function(body, target) { var globalcounter = 0; var concatstring = ''; for(var i=0,j=target.length;i<body.length;i++){ concatstring = body.substring(i-1,j); if(concatstring === target){ globalcounter += 1; concatstring = ''; } } return globalcounter; }; console.log( countInstances('abcabc', 'abc') ); // ==> 2 console.log( countInstances('ababa', 'aba') ); // ==> 2 console.log( countInstances('aaabbb', 'ab') ); // ==> 1
#22楼
var s = "1";replaced word var a = "HRA"; //have to replace var str = document.getElementById("test").innerHTML; var count = str.split(a).length - 1; for (var i = 0; i < count; i++) { var s = "1"; var a = "HRA"; var str = document.getElementById("test").innerHTML; var res = str.replace(a, s); document.getElementById("test").innerHTML = res; }
<input " type="button" id="Btn_Validate" value="Validate" class="btn btn-info" /> <div class="textarea" id="test" contenteditable="true">HRABHRA</div>
#23楼
有点晚了,但是假设我们有以下字符串:
var temp = "This is a string.";
首先,我们根据您要匹配的内容进行拆分,这将返回一个字符串数组。
var array = temp.split("is");
然后我们得到它的长度并减去1,因为split默认为大小为1的数组,因此每次发现一个出现时都会增加其大小。
var occurrenceCount = array.length - 1;
alert(occurrenceCount); //should output '2'
您还可以在一行中完成所有这些操作,如下所示:
alert("This is a string.".split("is").length - 1); //should output '2'
希望对您有帮助:D
#24楼
没人会看到这一点,但是最好偶尔恢复递归和箭头功能(这是双关语)
String.prototype.occurrencesOf = function(s, i) {
return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};
#25楼
此解决方案基于.replace()
方法,该方法接受RegEx作为第一个参数,并接受函数作为第二个参数 ,我们可以将其用作闭合以增加计数器...
/**
* Return the frequency of a substring in a string
* @param {string} string - The string.
* @param {string} string - The substring to count.
* @returns {number} number - The frequency.
*
* @author Drozerah https://gist.github.com/Drozerah/2b8e08d28413d66c3e63d7fce80994ce
* @see https://stackoverflow.com/a/55670859/9370788
*/
const subStringCounter = (string, subString) => {
let count = 0
string.replace(new RegExp(subString, 'gi'), () => count++)
return count
}
用法
subStringCounter("foofoofoo", "bar"); //0
subStringCounter("foofoofoo", "foo"); //3
#26楼
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 );
}
#27楼
只是对代码进行Rebecca Chernoff的解决方案 :-)
alert(("This is a string.".match(/is/g) || []).length);
#28楼
/** Function that count occurrences of a substring in a string;
* @param {String} string The string
* @param {String} subString The sub string to search for
* @param {Boolean} [allowOverlapping] Optional. (Default:false)
*
* @author Vitim.us https://gist.github.com/victornpb/7736865
* @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
* @see http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string/7924240#7924240
*/
function occurrences(string, subString, allowOverlapping) {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++n;
pos += step;
} else break;
}
return n;
}
用法
occurrences("foofoofoo", "bar"); //0
occurrences("foofoofoo", "foo"); //3
occurrences("foofoofoo", "foofoo"); //1
allowOverlapping
occurrences("foofoofoo", "foofoo", true); //2
火柴:
foofoofoo
1 `----´
2 `----´
单元测试
基准测试
要旨我进行了基准测试,其功能比gumbo发布的regexp match函数快10倍以上。 在我的测试字符串中,长度为25个字符。 出现了2个字符“ o”。 我在Safari中执行了1000000次。
Safari 5.1
基准测试>总执行时间:5617毫秒(正则表达式)
基准测试>总执行时间:881毫秒(我的功能快6.4倍)
Firefox 4
基准测试>总执行时间:8547毫秒(Rexexp)
Benchmark>总执行时间:634毫秒(我的功能快13.5倍)
编辑:我所做的更改
缓存的子串长度
在字符串中添加了类型转换。
添加了可选的“ allowOverlapping”参数
修复了“”空子字符串大小写正确的输出。