Hoe kan ik het aantal keren tellen dat een bepaalde string in een andere string voorkomt. Dit is bijvoorbeeld wat ik probeer te doen in Javascript:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
Antwoord 1, autoriteit 100%
De g
in de reguliere expressie (afkorting van global) zegt om de hele string te doorzoeken in plaats van alleen de eerste instantie te vinden. Dit komt twee keer overeen met is
:
var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);
Antwoord 2, autoriteit 21%
/** 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 https://stackoverflow.com/a/7924240/938822
*/
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;
}
Gebruik
occurrences("foofoofoo", "bar"); //0
occurrences("foofoofoo", "foo"); //3
occurrences("foofoofoo", "foofoo"); //1
Overlapping toestaan
occurrences("foofoofoo", "foofoo", true); //2
Wedstrijden:
foofoofoo
1 `----´
2 `----´
Eenheidstest
Benchmark
Ik heb een benchmarktest gedaan en mijn functie is meer dan 10 keer
sneller dan de regexp match-functie gepost door gumbo. In mijn test
string is 25 tekens lang. met 2 keer het karakter ‘o’. I
1 000 000 keer uitgevoerd in Safari.Safari 5.1
Benchmark> Totale uitvoeringstijd: 5617 ms (regexp)
Benchmark> Totale uitvoeringstijd: 881 ms (mijn functie 6,4x sneller)
Firefox 4
Benchmark> Totale uitvoeringstijd: 8547 ms (Rexexp)
Benchmark> Totale uitvoeringstijd: 634 ms (mijn functie 13,5x sneller)
Bewerken: wijzigingen die ik heb aangebracht
lengte subtekenreeks in cache
type-casting toegevoegd aan string.
optionele parameter ‘allowOverlapping’ toegevoegd
vaste correcte uitvoer voor “” lege subtekenreeks.
Samenvatting
Antwoord 3, autoriteit 13%
function countInstances(string, word) {
return string.split(word).length - 1;
}
console.log(countInstances("This is a string", "is"))
Antwoord 4, autoriteit 8%
Je kunt dit proberen:
var theString = "This is a string.";
console.log(theString.split("is").length - 1);
Antwoord 5, autoriteit 3%
Mijn oplossing:
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'));
Antwoord 6, autoriteit 2%
U kunt match
gebruiken om een dergelijke functie te definiëren:
String.prototype.count = function(search) {
var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
return m ? m.length:0;
}
Antwoord 7
De niet-regex-versie:
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
Antwoord 8
Gewoon code-golfen Rebecca Chernoff‘s oplossing🙂
alert(("This is a string.".match(/is/g) || []).length);
Antwoord 9
Voor iedereen die deze thread in de toekomst vindt, houd er rekening mee dat het geaccepteerde antwoord niet altijd de juiste waarde retourneert als je het generaliseert, omdat het zal stikken in regex-operators zoals $
en .
. Hier is een betere versie, die elkenaald aankan:
function occurrences (haystack, needle) {
var _needle = needle
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
return (
haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
).length
}
Antwoord 10
Probeer het
<?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>
Antwoord 11
Eenvoudige versie zonder regex:
var temp = "This is a string.";
var count = (temp.split('is').length - 1);
alert(count);
Antwoord 12
Niemand zal dit ooit zien, maar het is goed om af en toe de recursie- en pijlfuncties terug te brengen (woordspeling glorieus bedoeld)
String.prototype.occurrencesOf = function(s, i) {
return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};
Antwoord 13
ES2020 biedt een nieuwe MatchAll die in deze specifieke context van pas kan komen.
Hier maken we een nieuwe RegExp aan, zorg ervoor dat u ‘g’ doorgeeft aan de functie.
Converteer het resultaat met behulp van Array.from en tel de lengte, die 2 retourneert volgens de gewenste uitvoer van de oorspronkelijke aanvrager.
let strToCheck = RegExp('is', 'g')
let matchesReg = "This is a string.".matchAll(strToCheck)
console.log(Array.from(matchesReg).length) // 2
Antwoord 14
Dit is een heel oude thread die ik ben tegengekomen, maar aangezien velen hun antwoord hebben gegeven, is hier de mijne in de hoop iemand te helpen met deze eenvoudige code.
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);
Antwoord 15
function substrCount( str, x ) {
let count = -1, pos = 0;
do {
pos = str.indexOf( x, pos ) + 1;
count++;
} while( pos > 0 );
return count;
}
Antwoord 16
Je zou dit kunnen proberen
let count = s.length - s.replace(/is/g, "").length;
Antwoord 17
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
Antwoord 18
substr_count
vertaald naar Javascript vanuit php
- Locutus (pakket dat php naar JS vertaalt)
- substr_count (officiële pagina, code hieronder gekopieerd)
function substr_count (haystack, needle, offset, length) {
// eslint-disable-line camelcase
// discuss at: https://locutus.io/php/substr_count/
// original by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Brett Zamir (https://brett-zamir.me)
// improved by: Thomas
// example 1: substr_count('Kevin van Zonneveld', 'e')
// returns 1: 3
// example 2: substr_count('Kevin van Zonneveld', 'K', 1)
// returns 2: 0
// example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10)
// returns 3: false
var cnt = 0
haystack += ''
needle += ''
if (isNaN(offset)) {
offset = 0
}
if (isNaN(length)) {
length = 0
}
if (needle.length === 0) {
return false
}
offset--
while ((offset = haystack.indexOf(needle, offset + 1)) !== -1) {
if (length > 0 && (offset + needle.length) > length) {
return false
}
cnt++
}
return cnt
}
Bekijk Locutus’ vertaling van de substr_count-functie van Php
Antwoord 19
De parameters:
ustring: de superset-tekenreeks
countChar: de substring
Een functie om het voorkomen van subtekenreeksen in JavaScript te tellen:
function subStringCount(ustring, countChar){
var correspCount = 0;
var corresp = false;
var amount = 0;
var prevChar = null;
for(var i=0; i!=ustring.length; i++){
if(ustring.charAt(i) == countChar.charAt(0) && corresp == false){
corresp = true;
correspCount += 1;
if(correspCount == countChar.length){
amount+=1;
corresp = false;
correspCount = 0;
}
prevChar = 1;
}
else if(ustring.charAt(i) == countChar.charAt(prevChar) && corresp == true){
correspCount += 1;
if(correspCount == countChar.length){
amount+=1;
corresp = false;
correspCount = 0;
prevChar = null;
}else{
prevChar += 1 ;
}
}else{
corresp = false;
correspCount = 0;
}
}
return amount;
}
console.log(subStringCount('Hello World, Hello World', 'll'));
Antwoord 20
var str = 'stackoverflow';
var arr = Array.from(str);
console.log(arr);
for (let a = 0; a <= arr.length; a++) {
var temp = arr[a];
var c = 0;
for (let b = 0; b <= arr.length; b++) {
if (temp === arr[b]) {
c++;
}
}
console.log(`the ${arr[a]} is counted for ${c}`)
}
Antwoord 21
Itereer de tweede keer minder (net wanneer de eerste letter van de subtekenreeks overeenkomt) maar gebruikt nog steeds 2 for-lussen:
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"));
Antwoord 22
//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;
}