Use RegEx to count the number "a" in a string.
var string = 'aajlkjjskdjfAlsj;gkejflksajfjskda'; document.write(string.match(/a/gi).length);
Let me explain how this works:
string.match This is the 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 says: "Find character a." It is very simple. It also contains two flags: "g" and "i". "G" says to find ALL occurrences of the character "a". Otherwise, he will find only the first, and he will never count past number one. The second flag is "i". This makes RegEx match all cases of this character. If this flag (i) was not there, the above code will only count 4, because it will skip the capital letter "A" in the string. Due to the "i" it will match upper and lower case.
string.match returns an array of all matches, so we use the length method to retrieve the number of entries in the array. Just like that!
God is good Dec 03 '14 at 17:23 2014-12-03 17:23
source share