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_1开发者_JAVA百科09_all,mystring_110_mine,mystring_125_all"
how do i split this string in to an array
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"
});
Same, but loop
var myCommaStrings = myString.split(',');
var myUnderscoreStrings = [];
for (var i=0;i<myCommaStrings.length;i++)
myUnderscoreStrings[myUnderscoreStrings.length] = myCommaStrings[i].split('_');
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("_");
}
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
Umm, the same way you would your original example:
var mystring = "mystring_109_all,mystring_110_mine,mystring_125_all";
var myarray = mystring.split(",");
I've created a JavaScript functions-only library called FuncJS which has a function called split()
which would (hopefully) get the task done.
Read the docs and do download FuncJS, it's a very lightweight file.
<!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**
a b c d e f g
Arr[0]=a
精彩评论