[removed] How many times a character occurs in a string?

前端 未结 6 2110
傲寒
傲寒 2020-12-13 03:15

Is there a simple way to check how many times a character appears in a String?

6条回答
  •  余生分开走
    2020-12-13 03:53

    Use a RegEx to count the number of "a"s in a string.

    var string = 'aajlkjjskdjfAlsj;gkejflksajfjskda';
    
    document.write(string.match(/a/gi).length);

    Let me explain how this works:

    string.match This is a RegEx method. It searches for the specified RegEx inside the specified string (in this case, the string "string").

    (/a/gi) This is the actual RegEx. It reads, "find the character a." It's very simple. It also carries two flags, the "g" and the "i". The "g" says to find ALL occurences of the character "a". Otherwise it would only find the first one, and it would never count past the number one. The second flag is "i". It makes the RegEx match all cases of that character. If that flag (i) was not there, the code above would only count 4, because it would skip the uppercase "A" in the string. Because of the "i", it will match upper and lower case. Remove the "i" if you you want to match letter case.

    string.match returns an array of all of the matches, so we use the length method to retrieve the number of array entries. Simple as that!

提交回复
热议问题