Get the number of occurrences of a character in JavaScript

I have a line that divides some data using ',' . Now I want to count the occurrences of ',' on this line. I tried:

 var match = string.match('/[,]/i'); 

But it gives me null if I try to get the length of the match array. Any ideas?

+4
source share
7 answers

If you need to check the origin of a simple pattern as ",", then it is better not to use regular expressions.

Try:

 var matchesCount = string.split(",").length - 1; 
+20
source

Remove the quotation marks 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/

+5
source

This method claimed that regexp is the most efficient method.

Edit: However, the performance metric provided by Job in the comments show that the split method is faster. Therefore, I would recommend it these days.

But in any case, if you go to the regexp approach, you should know that if there are no matches, then String::match() returns null, not an empty array, as you might expect:

 > 'foo'.match(/o/g) [ 'o', 'o' ] > 'foo'.match(/o/g).length 2 > 'foo'.match(/x/g) null > 'foo'.match(/x/g).length TypeError: Cannot read property 'length' of null 

One easy way to handle this is to replace an empty array if the result is null:

 var count = (string.match(/,/g) || []).length; 

Or this avoids creating an empty array, but requires two lines of code:

 var match = string.match(/,/g); var count = match ? match.length : 0; 
+3
source

Count regex matches in javascript

you need the /g global flag

Edit: I don't need tics below.

 var count = string.match(/,/g).length; 
+1
source

This gives null because '/[,]/i' not a regular expression. As explained in MDN , if a non-regular expression is passed to string.match , then it will be converted to a regular expression using new Regex(obj) .

You want to pass the real regex object, /[,]/i (or just /,/i ). "1,2,3".match(/,/i) will work as you expect in terms of compliance.

However, as CyberKite pointed out, regex is redundant for these kinds of problems. The best solution is to split the line:

 var str = "1,2,3,4,5"; var len = str.split(",").length - 1; 
0
source
 function get_occurrence(varS,string){//Find All Occurrences c=(string.split(varS).length - 1); return c; } string="Hi, 1,2,3"; console.log(get_occurrence(",",string)); 

Use get_occurrence (varS, string) to find the occurrences of both characters and string in String.

0
source

Use the following code to separate some data using the ',' from the statement:

  var str = "Stack,Overflow,best,for,coder" var matchesCount = str.split(",").length; var vallueArray = str.split(',', matchesCount); var value1= ""; for (var i = 0 ; i < vallueArray.length; i++) { value1= value1+ vallueArray [i] + " "; } document.getElementById("txt1").value = value1; 
0
source

All Articles