Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of occurrences of a character in JavaScript [duplicate]

Tags:

javascript

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?

like image 245
UpCat Avatar asked Jul 15 '11 04:07

UpCat


People also ask

How do you count how many times a character is repeated in a string?

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.

How do you get the number of occurrences of a character in a string in JavaScript?

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.

How do you find duplicate characters in a given string in JavaScript?

function removeDuplicateCharacters(string) { return string . split('') . filter(function(item, pos, self) { return self. indexOf(item) == pos; }) .

How do you count the number of occurrences of a character in an array in JavaScript?

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 .


2 Answers

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;
like image 147
Chandu Avatar answered Sep 20 '22 03:09

Chandu


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/

like image 42
jfriend00 Avatar answered Sep 20 '22 03:09

jfriend00