Count the target character in a string

I have a line

file123,file456,file789 

I want to count the amount of time "," in this line, for example, for this line the answer should be 2

0
javascript
Apr 30 '14 at 10:05
source share
6 answers

There are many ways to do this, but here are a few examples :)

one.

 "123,123,123".split(",").length-1 

2.

 ("123,123,123".match(/,/g)||[]).length 
+2
Apr 30 '14 at 10:23
source share

A simple regex will give you the length:

 var str = "file123,file456,file789"; var count = str.match(/,/g).length; 
+3
Apr 30 '14 at 10:10
source share

You can use RegExp.exec() to save memory if you are dealing with a large string:

 var re = /,/g, str = 'file123,file456,file789', count = 0; while (re.exec(str)) { ++count; } console.log(count); 

Demo Comparative Comparison

Performance is about 20% lower than the solution using String.match() , but it helps if you're concerned about memory.

Update

Less sexy but faster:

 var count = 0, pos = -1; while ((pos = str.indexOf(',', pos + 1)) != -1) { ++count; } 

Demo

+2
Apr 30 '14 at 10:15
source share

Most likely, it’s faster to split the string based on the element you want, and then get the length of the resulting array.

 var haystack = 'file123,file456,file789'; var needle = ','; var count = haystack.split(needle).length - 1; 
+1
Apr 30 '14 at 10:08
source share

Since split must create another array, I would recommend writing a helper function like this

 function count(originalString, character) { var result = 0, i; for (i = 0; i < originalString.length; i += 1) { if (character == originalString.charAt(i)) { result +=1; } } return result; } 
+1
Apr 30 '14 at 10:11
source share
 var count = "file123,file456,file789".split(",").length - 1; 
0
Apr 30 '14 at 10:08
source share



All Articles