Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Short question. How can I convert a string to the JS array?

Look at the code:

var string = "0,1";
var array = [string];
alert(array[0]);

In this case, alert would popup a 0,1. When it would be an array, it would popup a 0, and when alert(array[1]); is called, it should popup the 1.

Is there any chance to convert such string into a JS array?

share|improve this question
    
Depending why you want this, strings and arrays are already very similiar (i.e. string[0] === '0' in your question), in most cases you can treat a string as an array of chars and use array methods on it. – Paul S. Nov 7 '12 at 15:19
    
@PaulS.: That will fail in IE8 and lower. – I Hate Lazy Nov 7 '12 at 16:00
    
possible duplicate of convert javascript comma separated string into an array – Baby Apr 8 '14 at 3:57
    
Best practice for support all types of strings. See here stackoverflow.com/a/32657055/2632619 – Andi AR Sep 18 '15 at 16:43
up vote 279 down vote accepted

For simple array members like that, you can use JSON.parse.

var array = JSON.parse("[" + string + "]");

This gives you an Array of numbers.

[0, 1]

If you use .split(), you'll end up with an Array of strings.

["0", "1"]

Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you'd need to use eval(), or a JavaScript parser.


If you want to use .split(), but you also want an Array of Numbers, you could use Array.prototype.map, though you'd need to shim it for IE8 and lower or just write a traditional loop.

var array = string.split(",").map(Number);
share|improve this answer
1  
Also be aware that JSON.parse(); is not available in IE6, IE7. I think in this case the String.split(','); is easier. – scunliffe Nov 7 '12 at 15:15
    
@scunliffe: True, a shim would be needed, or one could take the jQuery approach to shim it var array = (new Function("return [" + string + "];"))(). Using .split() is alright if Numbers aren't needed, otherwise you'd need to map the result. – I Hate Lazy Nov 7 '12 at 15:18
6  
@Downvoter: Try to describe what is wrong with the answer so that I can demonstrate how you're wrong. – I Hate Lazy Nov 7 '12 at 15:59
    
@I Hate Lazy This doesnt support object string.see here stackoverflow.com/a/32657055/2632619 – Andi AR Sep 18 '15 at 16:41
    
eval() worked for me – Farzad YZ Nov 30 '15 at 7:20

Split it on the , character;

var string = "0,1";
var array = string.split(",");
alert(array[0]);
share|improve this answer

If the string is already in list format, you can use the JSON.parse:

var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);
share|improve this answer

This is easily achieved in ES6;

You can convert strings to Arrays with Array.from('string');

Array.from("01")

will console.log

['0', '1']

Which is exactly what you're looking for.

share|improve this answer
2  
This should be the official answer – cancerbero Aug 20 at 14:51
    
This is awesome. I moved my code from JSON.parse to Array.from as am using ES6. Thank you Ray Kim – Eshwar Prasad Yaddanapudi Sep 27 at 7:49

For simple array members like that, you can use JSON.parse.

var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";

var array = JSON.parse("[" + listValues + "]");

This gives you an Array of numbers.

now you variable value is like array.length=1

Value output

array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes
share|improve this answer

you can use split. http://www.w3schools.com/jsref/jsref_split.asp

"0,1".split(',')

share|improve this answer

Convert all type of strings

var array = (new Function("return [" + str+ "];")());

Why above best practice , cause its accept string and objectstrings

var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

Result in console

enter image description here

Some practice doesnt support object strings

- JSON.parse("[" + string + "]"); // throw error

 - string.split(",") 
// unexpected result 
   ["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", "      {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"",    " CatGroupName:"Leather"", " Gender:"child"}"]
share|improve this answer

use the built-in map function with an anonymous function, like so:

string.split(',').map(function(n) {return Number(n);});

[edit] here's how you would use it

var string = "0,1";
var array = string.split(',').map(function(n) {
    return Number(n);
});
alert( array[0] );
share|improve this answer
1  
This is the most generally applicable answer. JSON can not be used for arbitrary delimiters (e.g. tab, space, etc) – javadba Feb 2 at 23:33
    
This won't work when your array values are string values that possible have a comma inside. For example: "123, 'a string with a , comma', 456". You could use a more complex regex to handle such cases correctly (for example something like suggested here). – Wilt May 9 at 12:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.