Comment compter l'occurrence de chaîne de caractères dans string?

Comment puis-je compter le nombre de fois qu'une chaîne particulière apparaît dans une autre chaîne. Par exemple, c'est ce que J'essaie de faire dans Javascript:

var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
453
demandé sur TruMan1 2010-10-24 22:39:15

25 réponses

le g dans l'expression régulière (abréviation de global ) dit de rechercher la chaîne entière plutôt que de trouver la première occurrence:

var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);

ça correspond à is deux fois. Et s'il n'y a pas d'allumettes, il renvoie 0 .

var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count);
775
répondu Rebecca Chernoff 2018-02-26 13:05:48
/** 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 /q/how-to-count-string-occurrence-in-string-37630/"";
    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;
}

Utilisation

occurrences("foofoofoo", "bar"); //0

occurrences("foofoofoo", "foo"); //3

occurrences("foofoofoo", "foofoo"); //1

allowOverlapping

occurrences("foofoofoo", "foofoo", true); //2

Correspond à:

  foofoofoo
1 `----´
2    `----´

Test Unitaire

de Référence", 151950920"

j'ai fait un test de référence et ma fonction est plus de 10 fois plus rapide que la correspondance regexp fonction Postée par gumbo. Dans mon test la chaîne est de 25 caractères. avec 2 occurences du caractère "o". Je exécuté 1 000 000 fois en Safari.

Safari 5.1

de Référence> temps Total d'exécution: 5617 ms (regexp)

de Référence> temps Total d'exécution: 881 ms (ma fonction 6,4 x plus rapide)

Firefox 4

Référence> temps Total d'exécution: 8547 ms (Rexexp)

de Référence> temps Total d'exécution: 634 ms (ma fonction 13,5 x plus rapide)


Edit: modifications que j'ai apporté

  • longueur de substrat mise en cache

  • ajouté le moulage par type à la chaîne.

  • ajouté optionnel "allowOverlapping" paramètre

  • sortie correcte fixe pour "" boîte de substrat vide.

GIST

195
répondu Vitim.us 2016-12-16 13:28:11
function countInstances(string, word) {
   return string.split(word).length - 1;
}
73
répondu Orbit 2017-12-11 16:15:39

Vous pouvez essayer ceci:

var theString = "This is a string.";
console.log(theString.split("is").length - 1);
64
répondu Freezy Ize 2016-07-08 18:13:53

ma solution:

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'));
28
répondu Gere 2016-07-08 18:33:26

vous pouvez utiliser match pour définir une telle fonction:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\+*?[^\]$(){}\|])/g, "\"), "g"));
    return m ? m.length:0;
}
17
répondu Gumbo 2011-07-05 20:46:40

Voici la fonction la plus rapide!

Pourquoi est-ce plus rapide?

  • Ne contrôle pas le char par char (à 1 exception)
  • utilise un while and increments 1 var (the char count var) vs. A pour vérifier la longueur de la boucle et incrémenter 2 var (habituellement var i et un var avec le char count)
  • utilise des var beaucoup moins
  • N'utilise pas regex!
  • utilise (espérons-le) hautement optimisé la fonction
  • Toutes les opérations sont combinés, car ils peuvent être, en évitant les ralentissements en raison de plusieurs opérations

    String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
    

Voici une version plus lente et plus lisible:

    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;
    };

celui-ci est plus lent à cause du compteur, des noms longs de var et de l'abus de 1 var.

Pour l'utiliser, il vous suffit de faire ceci:

    'The char "a" only shows up twice'.timesCharExist('a');

Edit: (2013/12/16)

ne pas utiliser avec Opera 12.16 ou plus! il faudra presque 2,5 fois plus que la solution regex!

sur chrome, Cette solution prendra entre 14 et 20ms pour 1.000.000 de caractères.

la solution regex prend 11-14ms pour la même quantité.

en utilisant une fonction (en dehors de String.prototype ) prendra environ 10-13ms.

Voici le code utilisé:

    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');

le résultat de toutes les solutions devrait être 100.000!

Note: Si vous voulez que cette fonction compte plus de 1 char, changez où est c=(c+'')[0] en c=c+''

7
répondu Ismael Miguel 2013-12-16 10:38:47

the non-regex version:

 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
7
répondu Faraz Kelhini 2018-03-22 18:02:48

Just code-golfing Rebecca Chernoff 's solution : -)

alert(("This is a string.".match(/is/g) || []).length);
7
répondu TMS 2018-07-11 21:32:54

var temp = "This is a string.";
console.log((temp.match(new RegExp("is", "g")) || []).length);
5
répondu Sunil Garg 2016-07-08 18:40:12

je pense que le but de regex est très différent de indexOf . indexOf trouve simplement l'occurence d'une certaine chaîne tandis que dans regex vous pouvez utiliser des caractères génériques comme [A-Z] qui signifie qu'il trouvera n'importe quel caractère capital dans le mot sans indiquer le caractère réel.

exemple:

 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);
3
répondu Simm 2016-07-14 00:34:10

String.prototype.Count = function (find) { return this.split(find).length - 1; } "This is a string.".Count("is");

Ce sera de retour 2.

3
répondu Fad Seck 2016-09-10 03:53:09

Super Vieux duper, mais j'avais besoin de faire quelque chose comme ça aujourd'hui et j'ai seulement pensé à le vérifier plus tard. Fonctionne assez rapide pour moi.

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;
};
2
répondu Jason Larke 2013-04-05 04:16:46
       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");

se Référer :- comptage d'une sous-chaîne apparaît dans la chaîne pour l'explication étape par étape.

2
répondu Ranju 2014-11-19 17:45:28

construit sur @Vittim.réponse des États-Unis ci-dessus. J'aime le contrôle que sa méthode me donne, le rendant facile à étendre, mais j'ai dû ajouter l'insensibilité de cas et limiter correspondances à des mots entiers avec un soutien pour la ponctuation. (par exemple, "salle de bain" est de "prendre un bain."mais pas de "bain")

la règle de ponctuation vient de: https://stackoverflow.com/a/25575009/497745 ( ) Comment puis-je supprimer toute ponctuation d'une chaîne en JavaScript en utilisant regex? )

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;
}

s'il vous plaît n'hésitez pas à modifier et à reformuler cette réponse si vous repérez des bugs ou des améliorations.

2
répondu Ayo I 2017-05-23 12:18:21

pour quiconque trouvera ce fil dans le futur, notez que la réponse acceptée ne retournera pas toujours la bonne valeur si vous la généralisez, car elle étouffera sur les opérateurs regex comme $ et . . Voici une meilleure version, qui peut manipuler n'importe quelle aiguille:

function occurrences (haystack, needle) {
  var _needle = needle
    .replace(/\[/g, '\[')
    .replace(/\]/g, '\]')
  return (
    haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
  ).length
}
2
répondu bcherny 2016-09-27 21:44:30

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));

utilisez get_occurrence(varS,string) pour trouver l'occurrence des deux caractères et de la chaîne dans une chaîne.

2
répondu Rahul Ranjan 2017-06-30 23:29:56

Essayer

<?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>
1
répondu The Clouds 2013-11-15 11:27:27

version Simple Sans regex:

var temp = "This is a string.";

var count = (temp.split('is').length - 1);

alert(count);
1
répondu Jorge Alberto 2016-06-08 13:21:07

maintenant c'est un fil très vieux que j'ai rencontré mais comme beaucoup ont poussé leurs réponses, voici le mien dans l'espoir d'aider quelqu'un avec ce code simple.

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[letter.length - 1];
var count;
for (var i = count = 0; i < search_value.length; count += (search_value[i++] == letter));
console.log(count);

Je ne suis pas sûr que ce soit la solution la plus rapide mais je l'ai préféré pour la simplicité et pour ne pas utiliser regex (Je n'aime pas les utiliser!)

0
répondu Tushar Shukla 2016-07-08 18:31:41

réponse à Leandro Batista : juste un problème avec l'expression regex.

 "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>
0
répondu PhilMaGeo 2017-10-19 11:13:07

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
0
répondu Kamal 2018-02-09 02:21:40

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>
0
répondu jithin 2018-03-01 12:24:50

un peu tard mais, en supposant que nous ayons la chaîne suivante:

var temp = "This is a string.";

d'abord, nous nous séparons sur ce que vous cherchez à assortir, cela vous ramènera un tableau de cordes.

var array = temp.split("is");

ensuite nous obtenons la longueur de celui-ci et soustrayons 1 à elle puisque split par défaut à un tableau de taille 1 et par conséquence augmente sa taille à chaque fois qu'il trouve un événement.

var occurrenceCount = array.length - 1;
alert(occurrenceCount); //should output '2'

vous pouvez également faire tout cela dans une ligne comme

alert("This is a string.".split("is").length - 1); //should output '2'

Espère que cela aide :D

0
répondu Juan Enrique Segebre 2018-04-18 03:24:06

essayez ceci:

function countString(str, search){
    var count=0;
    var index=str.indexOf(search);
    while(index!=-1){
        count++;
        index=str.indexOf(search,index+1);
    }
    return count;
}
-1
répondu Diogo Arenhart 2013-02-14 16:05:50