I have a rather specific problem.

I'm using ng-csv, and because it doesn't support nested arrays, I'm turning an array into a string.

Something like this:

[
 {"name":"Maria","chosen":false},
 {"name":"Jenny","chosen":false},
 {"name":"Ben","chosen":false},
 {"name":"Morris","chosen":false}
]

Turns into:

$scope.var = "Maria, Jenny, Ben, Morris"

My problem is that when I was using the array I was able to count the number of names in the array (which I need for UI reasons), but with the string it gets tricky.

Basically, I cannot count the number of words because some names might include last name, but I thought I could count commas, and then add 1.

Any pointers on how to do just that?

share|improve this question
    
commas = str.length - str.replace(/,/g, "").length; – Alex K. Dec 22 '14 at 18:41
up vote 2 down vote accepted

If you need names itself - you may use method split of String class:

var str = "Maria, Jenny, Ben, Morris";
var arr = str.split(','); // ["Maria", " Jenny", " Ben", " Morris"]
var count = arr.length; // 4
share|improve this answer
    
I guess I can't NOT upvote your solution. :) – rchang Dec 22 '14 at 18:45
    
Thanks to your solution I realized I can count names before converting the array I already had to string : ) – Eric Mitjans Dec 22 '14 at 19:07
var str = "Maria, Jenny, Ben, Morris";
var tokens = str.split(",");

The number of tokens should be captured in tokens.length. Alternately, if you don't actually need to work with the tokens directly:

var nameCount = str.split(",").length;
share|improve this answer

Why not use regex?

var _string = "Mary, Joe, George, Donald";

_string.match(/,/g).length // 3
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.