Javascript split

I can use JavaScript markup to place comma-separated elements in an array:

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

What I mean is a little more complicated. I have this line separated by commas:

 "mystring_109_all,mystring_110_mine,mystring_125_all" 

how to split this string into an array

+7
javascript split
source share
7 answers

You can provide a regex for split () to separate a comma or underscore, use the following:

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

If you are after something more dynamic, you can try something like "Search and not replace," 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" }); 
+11
source share

Same but loop

 var myCommaStrings = myString.split(','); var myUnderscoreStrings = []; for (var i=0;i<myCommaStrings.length;i++) myUnderscoreStrings[myUnderscoreStrings.length] = myCommaStrings[i].split('_'); 
+2
source share

Throwing wild guesses if your specification is not completed:

 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("_"); } 
+1
source share

If you want to break the comma and then underscores, you will 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 separate commas or underscores, you can separate it with a regular expression, but sometimes this can be a mistake. Here's a page for reading on issues: http://blog.stevenlevithan.com/archives/cross-browser-split

+1
source share

Umm, just like in your original example:

 var mystring = "mystring_109_all,mystring_110_mine,mystring_125_all"; var myarray = mystring.split(","); 
0
source share

I created a JavaScript function library called FuncJS , which has a function called split() , which (hopefully) the task is completed.

Read the documents and download FuncJS, it is a very light file.

0
source share
 <!DOCTYPE html> <html> <body> <p>Question is var str = "a,b,c,d,e,f,g"; </p> <button onclick="myFunction()">Split Button</button> <p id="demo"></p> <p id="demo1"></p> <script> var text = ""; function myFunction() { var str = "a,b,c,d,e,f"; var arr = str.split(","); for(var i = 0; i<arr.length; ++i){ text += arr[i] +" "; document.getElementById("demo").innerHTML = text; } document.getElementById("demo1").innerHTML = arr[0]; } </script> </body> </html> **Answer** abcdefg Arr[0]=a 
0
source share

All Articles