2

I am trying to convert a comma separated string into an array using the split method(Convert comma separated string to array).

This is the code:

var nameList = "milk,sugar,flour";
var nameArray = nameList.split(',');

document.write('The nameList is: ' + nameList);
document.write('<br />');
document.write('The nameArray is: ' + nameArray);

This is the output:

The nameList is: milk,sugar,flour
The nameArray is: milk,sugar,flour

It looks to me like it is still a string separated by commas. Why is the comma-separated string not converting to an array using split() in javaScript?

3 Answers 3

6

It's an array. Array#toString produces the comma-separated output.

Try this:

[3, 4, 'b'].toString(); 

If you use console.log instead of document.write to inspect nameArray, you'll see that it is an array.

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

Comments

0

thats the way how JAVASCRIPT shoes an array

it did convert it

but you told JS to display it

so thats what he does.

proof:

nameArray[0]====>milk

nameArray[1]====>sugar

Comments

0

When you implicitly convert the array to a string by appending it to a string, it displays the array.toString() which uses commas. You can override this if you want.

if you do this instead, it will show the properly annotated version.

 JSON.stringify( nameArray ,"\t")

Comments

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.