Count the number of occurrences of a character in a string in Javascript

后端 未结 30 2394
礼貌的吻别
礼貌的吻别 2020-11-22 02:33

I need to count the number of occurrences of a character in a string.

For example, suppose my string contains:

var mainStr = \"str1,str2,str3,str4\";         


        
相关标签:
30条回答
  • 2020-11-22 03:21

    I have updated this answer. I like the idea of using a match better, but it is slower:

    console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3
    
    console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4
    

    jsfiddle

    Use a regular expression literal if you know what you are searching for beforehand, if not you can use the RegExp constructor, and pass in the g flag as an argument.

    match returns null with no results thus the || []

    The original answer I made in 2009 is below. It creates an array unnecessarily, but using a split is faster (as of September 2014). I'm ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match.

    Old answer (from 2009):

    If you're looking for the commas:

    (mainStr.split(",").length - 1) //3
    

    If you're looking for the str

    (mainStr.split("str").length - 1) //4
    

    Both in @Lo's answer and in my own silly jsperf test split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.

    0 讨论(0)
  • 2020-11-22 03:22

    The fastest method seems to be via the index operator:

    function charOccurances (str, char)
    {
      for (var c = 0, i = 0, len = str.length; i < len; ++i)
      {
        if (str[i] == char)
        {
          ++c;
        }
      }
      return c;
    }
    
    console.log( charOccurances('example/path/script.js', '/') ); // 2

    Or as a prototype function:

    String.prototype.charOccurances = function (char)
    {
      for (var c = 0, i = 0, len = this.length; i < len; ++i)
      {
        if (this[i] == char)
        {
          ++c;
        }
      }
      return c;
    }
    
    console.log( 'example/path/script.js'.charOccurances('/') ); // 2

    0 讨论(0)
  • 2020-11-22 03:22

    The following uses a regular expression to test the length. testex ensures you don't have 16 or greater consecutive non-comma characters. If it passes the test, then it proceeds to split the string. counting the commas is as simple as counting the tokens minus one.

    var mainStr = "str1,str2,str3,str4";
    var testregex = /([^,]{16,})/g;
    if (testregex.test(mainStr)) {
      alert("values must be separated by commas and each may not exceed 15 characters");
    } else {
      var strs = mainStr.split(',');
      alert("mainStr contains " + strs.length + " substrings separated by commas.");
      alert("mainStr contains " + (strs.length-1) + " commas.");
    }
    
    0 讨论(0)
  • 2020-11-22 03:23

    A quick Google search got this (from http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript)

    String.prototype.count=function(s1) { 
        return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
    }
    

    Use it like this:

    test = 'one,two,three,four'
    commas = test.count(',') // returns 3
    
    0 讨论(0)
  • 2020-11-22 03:24

    I know this might be an old question but I have a simple solution for low-level beginners in JavaScript.

    As a beginner, I could only understand some of the solutions to this question so I used two nested FOR loops to check each character against every other character in the string, incrementing a count variable for each character found that equals that character.

    I created a new blank object where each property key is a character and the value is how many times each character appeared in the string(count).

    Example function:-

    function countAllCharacters(str) {
      var obj = {};
      if(str.length!==0){
        for(i=0;i<str.length;i++){
          var count = 0;
          for(j=0;j<str.length;j++){
            if(str[i] === str[j]){
              count++;
            }
          }
          if(!obj.hasOwnProperty(str[i])){
            obj[str[i]] = count;
          }
        }
      }
      return obj;
    }
    
    0 讨论(0)
  • 2020-11-22 03:25

    I'm using Node.js v.6.0.0 and the fastest is the one with index (the 3rd method in Lo Sauer's answer).

    The second is:

    function count(s, c) {
      var n = 0;
      for (let x of s) {
        if (x == c)
          n++;
      }
      return n;
    }

    0 讨论(0)
提交回复
热议问题