i like to split a string depending on "," character using JavaScript
example
var mystring="1=name1,2=name2,3=name3";
need output like this
1=name1
2=name2
3=name3
-
-1: A Google search for exactly this phrase ("JavaScript split function") would have yielded several results explaining how to do this.Fyodor Soikin– Fyodor Soikin2010年06月10日 13:44:23 +00:00Commented Jun 10, 2010 at 13:44
-
+1 I rely on StackOverflow because I trust the community to have concise, correct answers to simple questions like this.Sean Kendle– Sean Kendle2014年01月03日 20:33:01 +00:00Commented Jan 3, 2014 at 20:33
2 Answers 2
var list = mystring.split(',');
Now you have an array with ['1=name1', '2=name2', '3=name3']
If you then want to output it all separated by spaces you can do:
var spaces = list.join("\n");
Of course, if that's really the ultimate goal, you could also just replace commas with spaces:
var spaces = mystring.replace(/,/g, "\n");
(Edit: Your original post didn't have your intended output in a code block, so I thought you were after spaces. Fortunately, the same techniques work to get multiple lines.)
2 Comments
Just use string.split() like this:
var mystring="1=name1,2=name2,3=name3";
var arr = mystring.split(','); //array of ["1=name1", "2=name2", "3=name3"]
If you the want string version of result (unclear from your question), call .join() like this:
var newstring = arr.join(' '); //(though replace would do it this example)
Or loop though, etc:
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}