问题
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";
回答1:
myString.split(',').length
回答2:
var mystring = "1,2,3,4";
var elements = mystring.split(',');
return elements.length;
回答3:
First split it, and then count the items in the array. Like this:
"1,2,3,4".split(/,/).length;
回答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
来源:https://stackoverflow.com/questions/3065941/count-the-elements-in-string