I have a string that devides some data using ','
. Now I want to count the occurences of ','
in that string. I tried:
var match = string.match('/[,]/i');
But this gives me null If I try to get the length of the match array. Any ideas?
Using Counter Array In the following Java program, we have used the counter array to count the occurrence of each character in a string. We have defined a for loop that iterates over the given string and increments the count variable by 1 at index based on character.
Approach 2: In this approach, we use nested for loop to iterate over string and count for each character in the string. First initialize count with value 0 for ith value of string. Now we iterate over string if ith value matches with the character, increase the count value by 1. Finally, print the value of count.
function removeDuplicateCharacters(string) { return string . split('') . filter(function(item, pos, self) { return self. indexOf(item) == pos; }) .
To count the occurrences of each element in an array:Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .
If you need to check the occurances of a simple pattern as "," then better don't use regular expressions.
Try:
var matchesCount = string.split(",").length - 1;
Remove the quotes and add the g flag:
var str = "This, is, another, word, followed, by, some, more";
var matches = str.match(/,/g);
alert(matches.length); // 7
jsfiddle here: http://jsfiddle.net/jfriend00/hG2NE/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With