1

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
2
  • -1: A Google search for exactly this phrase ("JavaScript split function") would have yielded several results explaining how to do this. Commented 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. Commented Jan 3, 2014 at 20:33

2 Answers 2

10
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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Can someone confirm that string.split() is available on most browsers (IE 8 and above?) I cant find any information about it online.
Yes, String.split is a core JavaScript feature that's available in all major browsers.
3

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]);
}

You can play with it a bit here

1 Comment

Please try not to use W3CSchools as a reference, in general. Their information is often out of date, unreliable and they are in no way affiliated with the W3C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.