简体   繁体   English

用Java脚本计算字符串中的逗号(AngularJS / Lodash)

[英]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. 我正在使用ng-csv,并且由于它不支持嵌套数组,因此我将数组转换为字符串。

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. 我的问题是,当我使用数组时,我能够计算数组中的名称数量(出于UI原因,我需要使用该名称),但是使用字符串会变得很棘手。

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. 基本上,我无法计算单词的数量,因为某些名称可能包括姓氏,但我认为我可以计算逗号,然后加1。

Any pointers on how to do just that? 关于如何做到这一点的任何指示?

If you need names itself - you may use method split of String class: 如果您本身需要名称-您可以使用String类的方法split

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 . 令牌数应在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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