6

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?

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

7 Answers7

21

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;
Chandu
  • 81,493
  • 19
  • 133
  • 134
  • 2
    Off by one: if you want to count the occurences of "," you've to do -1 – stivlo Jul 15 '11 at 04:48
  • https://gist.github.com/lsauer/2757250 (mentioned in the answer lower down this page) suggests that split() is inefficient, and should be avoided on large strings. – Darren Cook May 25 '17 at 09:17
  • I tried creating some benchmarks, looks like `split(',').length-1` is fastest. Can't speak for memory overhead though https://run.perf.zone/view/Count-occurrences-of-single-char-in-a-string-1506617641964 – Job Sep 28 '17 at 17:08
5

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/

Baldrick
  • 23,882
  • 6
  • 74
  • 79
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • good catch to remove the quotes, otherwise is a String and not a regular expression, but you've to use /g otherwise only the first match is returned. also /i is useless since there is no uppercase comma. – stivlo Jul 15 '11 at 04:51
  • I've had g in my answer for awhile including in the jsfiddle. – jfriend00 Jul 15 '11 at 04:53
  • Always like the jsfiddle links +1 – Ray Toal Jul 15 '11 at 04:54
  • @jfriend00 probably I loaded the page a while ago, and I was looking at the answers without refreshing it. I also edit often. +1 now that is fixed. – stivlo Jul 15 '11 at 04:56
3

This gist claimed that regexp was the most efficient technique.

Edit: However the performance benchmark provided by Job in the comments suggest that the split technique is now faster. So I would recommend that nowadays.

But anyway, if you do go with the regexp approach, you should be aware that if there are no matches, then String::match() returns null, and 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 simple way to deal with this is to substitute an empty array if the result is null:

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

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

var match = string.match(/,/g);
var count = match ? match.length : 0;
joeytwiddle
  • 29,306
  • 13
  • 121
  • 110
  • 1
    I made took (most of) the code in that gist and made a benchmark: https://run.perf.zone/view/Count-occurrences-of-single-char-in-a-string-1506617641964 Looks like `split(',').length-1)` is currently faster by a *large* margin! On my machine it's 60x faster than the second option in Chrome, and 10x faster on Firefox. No idea about memory overhead though. – Job Sep 28 '17 at 17:09
  • Interesting, thanks for the perf. Perhaps the engine's efficiency with temporary objects has increased, so now the cost of creating a new regexp dominates. I wonder if the results would be any different if the regexp was defined only once and reused many times. – joeytwiddle Oct 02 '17 at 07:06
  • 1
    The regex version is still slower: https://run.perf.zone/view/Count-occurrences-of-single-char-in-a-string-v21-1516516301656 – Job Jan 21 '18 at 06:33
1

Count number of matches of a regex in Javascript

you need the /g global flag

Edit: I didn't need the 'ticks' below.

var count = string.match(/,/g).length; 
Community
  • 1
  • 1
agent-j
  • 27,335
  • 5
  • 52
  • 79
0
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 occurrence of both characters and string in a String.

  • 1
    Hello, welcome to SO. Please do not add an answer that just repeats an already existing one. Instead, upvote the one that is already there. I know that for the moment you don't have enough rep for that (15), but in this case the best approach is to bookmark this page and, when you have enough rep, come back here and upvote. Otherwise, as frustrating as it may be (we've all been there!), just let it go. But please do not post an answer that doesn't add anything to what is already there. Thank you! – Fabio says Reinstate Monica Jul 01 '17 at 00:03
0

Use the following code to divide some data using ',' from a 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;
Sumant Singh
  • 904
  • 1
  • 14
  • 16
0

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

What you want is to pass the actual regex object, /[,]/i (or simply /,/i). "1,2,3".match(/,/i) will work as you expect in terms of matching.

However, as Cybernate pointed out, a regex is overkill for this kind of problem. A better solution is to split the string:

var str = "1,2,3,4,5";
var len = str.split(",").length - 1;
rubergly
  • 878
  • 8
  • 20