Steve Kim
Steve Kim

Reputation: 5591

jQuery get number of values

So, I have the following js:

var my_content = data.number;
alert(my_content);

Which I get the following alert: "1,2,3,4,5,6"

So, there are 6 values in this variable.

Problem

I want to get the number of values for for function:

var my_content = data.number;
    alert(my_content);
var length = data.number.length;
    alert(length);

For the my_content, I get 1,2,3,4,5,6 (Good).

For the length, I get 11 (bad). So it looks like it is counting every single characters.

How do I get the number of values?

EDIT

Just realized that there is a comma at the end of the value ""1,2,3,4,5,6,"

Upvotes: 0

Views: 37

Answers (3)

guest271314
guest271314

Reputation: 1

Try using String.prototype.match() with RegExp /[^,]/g to match characters that are not ,

var n = "1,2,3,4,5,6".match(/[^,]/g);
console.log(n.length);

Upvotes: 1

Drew Kennedy
Drew Kennedy

Reputation: 4168

Another option is to use the replace() function with a little regex:

var my_content = "1,2,3,4,5,6"
var getLength = my_content.trim().replace(/,/g, "").length;
console.log(getLength);//prints 6

To meet the new requirement of your string ending with ,, you can use trim() to eliminate any whitespace. The regex will do the rest.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190915

It sounds like its a string and you can use data.content.split(',') to get an array, but it will be an array of strings.

Upvotes: 1

Related Questions