Asim Zaidi
Asim Zaidi

Reputation: 28354

Count the elements in string

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";

Upvotes: 12

Views: 25628

Answers (5)

Arshad Jilani
Arshad Jilani

Reputation: 121

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;

Upvotes: 0

0x6A75616E
0x6A75616E

Reputation: 4726

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

Upvotes: 4

erjiang
erjiang

Reputation: 45757

var mystring = "1,2,3,4";
var elements = mystring.split(',');
return elements.length;

Upvotes: 8

Wolph
Wolph

Reputation: 80111

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

"1,2,3,4".split(/,/).length;

Upvotes: 3

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

myString.split(',').length

Upvotes: 18

Related Questions