tags:

views:

216

answers:

6

Hi,

I'm curious, how would you test a string and say "yep, that is a comma delimited list!" I'm not so worried about the 'comma delimited' part more that this string has more than one item in it?

Thanks, R.

+8  A: 

How about:

stringObject.indexOf(",") >= 0
George Phillips
Whilst this will ensure the string will parse as a CSV, to determine if it *should* be is another story.
alex
A: 

You could also just go like:

var words = yourString.split(',');
for(var i=0;i<words.length;++i) {
  doSomething(words[i]);
}
Andrew Johnson
A: 

Another solution:

(string.split(",").length > 1)

Steve

Steve Harrison
+2  A: 

To check if the string has more than one item, try something like:

str.split(",").length > 1

... although, as suggested in a comment, correct parsing is likely to be bit more complicated than this for the general case.

Edit:

whoops, misread language as Java - sorry.

harto
Why are Java CSV parsers going to help in JavaScript? They're completely different languages.
Steve Harrison
+1  A: 

Ask the string very politely if it's a comma delimited list. Perhaps even take it out for tea or an alcoholic beverage if it's open to that sort of thing. Just don't be too nice as you may end up in a long term relationship with it and end up marrying it. At which point it will slowly drain the life out of you and spend all of your money... but at least you can have intercourse with it.

Brian Dilley
Funny, but also stupid. Have an upvote to offset the downvotes that will most likely come.
alex
BTW, I meant the post was stupid, not you, in case that needed clarifying :)
alex
I prefer to add my joke answers as comments - that way no-one can downvote you for them.
harto
I prefer to give an answer with a joke in there somewhere :)
alex
Alex, why do you think the post was 'stupid?' Its a legitimate questions isn't it? If you think this is stupid and trivial why reply?
flavour404
+1  A: 

Be very careful if you are just splitting on a comma for a csv list as fields can actually contain commas and are encased by quotes i.e.
Name,Age
"doe, jane",18
"bob, jim",20

If it isn't for a csv perhaps you should be using an array or an object to hold the values?

rezzif
+1 useful advice
alex
Thanks, as alex said very useful advice. The only thing I can say in my defence is that I know that there will only be one item in the list (so its not really a list, just one item!) unless it comes from a particular source, in which case then it is something else, which I want to catch. Sounds odd I know, but that's the way its designed...Not my code, just trying to make it work.
flavour404
Do you have some sample data of what you'll be expecting? Will it just be a bunch of numbers or more csv like?
rezzif