Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 764
vishnu Avatar asked Aug 23 '10 14:08

vishnu


2 Answers

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"
});
like image 88
Andy E Avatar answered Oct 03 '22 12:10

Andy E


Same, but loop

var myCommaStrings = myString.split(','); 
var myUnderscoreStrings = []; 
for (var i=0;i<myCommaStrings.length;i++) 
  myUnderscoreStrings[myUnderscoreStrings.length] = myCommaStrings[i].split('_');
like image 27
mplungjan Avatar answered Oct 03 '22 11:10

mplungjan