12

I have a string that has comma separated values. How can I count how many elements in the string separated by comma? e.g following string has 4 elements

string = "1,2,3,4";
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221
  • Very similar to http://stackoverflow.com/questions/881085/count-the-number-of-occurances-of-a-character-in-a-string-in-javascript though not an exact duplicate. – Mark Byers Jun 17 '10 at 22:01

5 Answers5

18

myString.split(',').length

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67
8
var mystring = "1,2,3,4";
var elements = mystring.split(',');
return elements.length;
erjiang
  • 44,417
  • 10
  • 64
  • 100
4

All of the answers suggesting something equivalent to myString.split(',').length could lead to incorrect results because:

"".split(',').length == 1

An empty string is not what you may want to consider a list of 1 item.

A more intuitive, yet still succinct implementation would be:

myString.split(',').filter((i) => i.length).length

This doesn't consider 0-character strings as elements in the list.

"".split(',').filter((i) => i.length).length
0

"1".split(',').filter((i) => i.length).length
1

"1,2,3".split(',').filter((i) => i.length).length
3

",,,,,".split(',').filter((i) => i.length).length
0
0x6A75616E
  • 4,696
  • 2
  • 33
  • 57
  • Note that browser support for arrow functions is still limited: http://caniuse.com/#feat=arrow-functions For the time being I would recommend a regular function instead – Wolph Nov 06 '17 at 10:28
  • You're right @Wolph. Looks like IE11 still has a 12% marketshare globally today. – 0x6A75616E Nov 07 '17 at 18:23
3

First split it, and then count the items in the array. Like this:

"1,2,3,4".split(/,/).length;
Wolph
  • 78,177
  • 11
  • 137
  • 148
  • It's not wrong, it's simply a different definition. Empty string is also a value ;) Try ",," for example. – Wolph Nov 04 '17 at 18:28
  • Yes, but would you say that in most use cases a single empty string would be considered a list of 1 value? so.. the count of items in "a" equals the count of items in ""? – 0x6A75616E Nov 04 '17 at 22:29
  • I wouldn't say most but definitely often enough. If there is no value you probably don't want to run the function at all – Wolph Nov 04 '17 at 23:30
0

First You need to convert the string to an array using split, then get the length of the array as a count, Desired Code here.

var string = "1,2,3,4";
var desiredCount  = string.split(',').length;