views:

75

answers:

6
+2  Q: 

javascript split

I can use JavaScript's split to put a comma-separated list of items in an array:

var mystring = "a,b,c,d,e";
var myarray = mystring.split(",");

What I have in mind is a little more complicated. I have this comma separated string:

"mystring_109_all,mystring_110_mine,mystring_125_all"

how do i split this string in to an array

+1  A: 

1

org.life.java
why one down vote [from 2 to 1]?
org.life.java
+1  A: 

Same, but loop

var myCommaStrings = myString.split(','); 
var myUnderscoreStrings = []; 
for (var i=0;i<myCommaStrings.length;i++) 
  myUnderscoreStrings[myUnderscoreStrings.length] = myCommaStrings[i].split('_');
mplungjan
+1  A: 

Throwing a wild guess, given your spec isn't complete:

var mystring = "mystring_109_all,mystring_110_mine,mystring_125_all";
var myarray = mystring.split(",");
for (var i = 0; i < myarray.length; i++) {
  myarray[i] = myarray[i].split("_");
}
Jamie Wong
+1  A: 

If you want to split on commas and then on underscores, you'd have to iterate over the list:

var split1 = theString.split(',');
var split2 = [];
for (var i = 0; i < split1.length; ++i)
  split2.push(split1[i].split('_'));

If you want to split on commas or underscores, you can split with a regex, but that's sometimes buggy. Here's a page to read up on the issues: http://blog.stevenlevithan.com/archives/cross-browser-split

Pointy
A: 

Umm, the same way you would your original example:

var mystring = "mystring_109_all,mystring_110_mine,mystring_125_all";
var myarray = mystring.split(",");
michael
+3  A: 

You can provide a regular expression for split(), so to split on a comma or an underscore, use the following:

var mystring = "mystring_109_all,mystring_110_mine,mystring_125_all";
var myarray  = mystring.split(/[,_]/);

If you're after something more dynamic, you might want to try something like "Search and don't replace", a method of using the replace() function to parse a complex string. For example,

mystring.replace(/(?:^|,)([^_]+)_([^_]+)_([^_]+)(?:,|$)/g,
  function ($0, first, second, third) {
    // In this closure, `first` would be "mystring",
    // `second` would be the following number,
    // `third` would be "all" or "mine"
});
Andy E
shouldn't that be mystring.split(/,|_/);
Ken
Thanks for the link to the post - haven't seen that before. Good to know.
Jamie Wong
or even mystring.split(/[,_]/);
Ken
@Ken: yes, I meant to put `[,_]` - thanks for pointing that out, I'm a bit off my game today ;)
Andy E
@Andy - gotta get your head back, dude
Matt Ball
thank u for u r reply
vishnu