简体   繁体   中英

Counting commas in a string with Javascript (AngularJS/Lodash)

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?

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

Why not use regex?

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

_string.match(/,/g).length // 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM