451

How can I convert a string to a JavaScript array?

Look at the code:

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

In this case alert shows 0,1. If it where an array, it would show 0. And if alert(array[1]) is called, it should pop-up 1

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

Gass
  • 7,536
  • 3
  • 37
  • 41
Scott
  • 5,991
  • 15
  • 35
  • 42
  • 1
    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 07 '12 at 15:19
  • 1
    @PaulS.: That will *fail* in IE8 and lower. – I Hate Lazy Nov 07 '12 at 16:00
  • 1
    possible duplicate of [convert javascript comma separated string into an array](http://stackoverflow.com/questions/2858121/convert-javascript-comma-separated-string-into-an-array) – Baby Apr 08 '14 at 03:57
  • 1
    Best practice for support all types of strings. See here http://stackoverflow.com/a/32657055/2632619 – Andi AR Sep 18 '15 at 16:43

17 Answers17

792

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);
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • 6
    Also be aware that `JSON.parse();` is not available in IE6, IE7. I think in this case the `String.split(',');` is easier. – scunliffe Nov 07 '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 07 '12 at 15:18
  • 14
    @Downvoter: Try to describe what is wrong with the answer so that I can demonstrate how you're wrong. – I Hate Lazy Nov 07 '12 at 15:59
  • @I Hate Lazy This doesnt support object string.see here http://stackoverflow.com/a/32657055/2632619 – Andi AR Sep 18 '15 at 16:41
  • @FarzadYZ Be careful with that (using `eval`). If the array contains values from client side input this will be insecure. – Wilt May 09 '16 at 12:01
  • @Wilt Actually `eval` is always a security concern – Farzad Yousefzadeh May 10 '16 at 06:09
  • Don't use `JSON.parse` approach, it's never wise to form and evaluate strings into JS. Use `split`+`map`, it's better and elegant. – Onur Yıldırım Aug 11 '16 at 13:05
  • `JSON.parse()` worked so perfectly for me. Thank you! Here is my case: receivedValue is` "[{name:"Eshwar", area:"Hyd"},{name:"Prasad", area:"India"}]` So for my unittest case, i did `assert` using `_.isArray(JSON.parse(receivedValue))` – Eshwar Prasad Yaddanapudi Sep 27 '16 at 07:44
  • `string.split(','); `OR `for of & push` –  Aug 30 '17 at 02:27
  • bad solution! more info seeing `https://github.com/gildata/RAIO/issues/116#issuecomment-325901359` –  Aug 30 '17 at 08:17
  • There is an error in this answer. `"0,1".split()` returns `["0,1"]` and **not** `["0", "1"]`. Use `"0,1".split(",")` to return `["0", "1"]` – pldg Jul 04 '18 at 20:33
  • this solution not work any more – xgqfrms Mar 10 '22 at 04:43
  • JSON.parse dont work for ending comma : `["hbhb, uih", "jggk, ;yg, ugu",]` – ishandutta2007 Jun 26 '23 at 05:35
158

Split it on the , character;

var string = "0,1";
var array = string.split(",");
alert(array[0]);
Alex K.
  • 171,639
  • 30
  • 264
  • 288
102

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.

Kip
  • 107,154
  • 87
  • 232
  • 265
Ray Kim
  • 1,931
  • 1
  • 13
  • 25
  • 3
    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 '16 at 07:49
  • console.log(typeof Data); //string ========== var myArray = Array.from(Data); ============ console.log(typeof myArray); //Object doesn't support property or method 'from' ========== Why Is that? – Janatbek Orozaly Feb 17 '17 at 22:19
  • 1
    This is NOT supported in any version of IE. be careful – 29er Apr 28 '17 at 16:43
  • 2
    But `Array.from("0, 1, 233")` will return `["0", ",", " ", "1", ",", " ", "2", "3", "3"]`, what if I want `[0, 1, 233] ` ? – Tina Chen Jun 20 '17 at 07:04
  • 1
    bad solution! more info seeing `https://github.com/gildata/RAIO/issues/116#issuecomment-325901359` –  Aug 30 '17 at 08:16
  • 29
    This is converting every single character as an array element. But we need only comma separated strings to be array elements. So not a valid solution. – Edison D'souza Sep 28 '17 at 07:23
  • 1
    _Is_ there a syntax for converting a comma separated string into a number array using es6 features? – Arnav Borborah Feb 28 '18 at 21:55
  • 1
    This method is only reliable when argument is a `Set` of strings. – vhs Oct 25 '19 at 06:14
78

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);
otaviodecampos
  • 1,586
  • 16
  • 10
29

Convert all type of strings

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



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"}"]
Andi AR
  • 2,678
  • 2
  • 23
  • 28
23

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
Raghav Chaubey
  • 231
  • 2
  • 3
20

You can use split

Reference: http://www.w3schools.com/jsref/jsref_split.asp

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

Akash Joshi
  • 598
  • 1
  • 5
  • 15
dm03514
  • 54,664
  • 18
  • 108
  • 145
19

Another option using the ES6 is using Spread syntax.

var convertedArray = [..."01234"];

var stringToConvert = "012";
var convertedArray  = [...stringToConvert];
console.log(convertedArray);
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
12

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] );
Dan Mantyla
  • 1,840
  • 1
  • 22
  • 33
  • 1
    This is the most generally applicable answer. JSON can not be used for arbitrary delimiters (e.g. tab, space, etc) – WestCoastProjects Feb 02 '16 at 23:33
  • 1
    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](http://stackoverflow.com/questions/11456850/split-a-string-by-commas-but-ignore-commas-within-double-quotes-using-javascript)). – Wilt May 09 '16 at 12:06
  • @Wilt well no it wouldn't, but yeah you could use regex to fix that – Dan Mantyla Feb 14 '18 at 20:21
  • 2
    I didn't mean to criticize your answer, but I wrote this because I used your solution and ran into this issue myself. Thought of leaving the comment for others possibly running into similar problems. – Wilt Feb 15 '18 at 17:53
  • 2
    Could be shortened as follows `string.split(',').map(Number)` – ya.teck May 28 '22 at 16:55
5

I remove the characters '[',']' and do an split with ','

let array = stringObject.replace('[','').replace(']','').split(",").map(String);
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
Samuel Seda
  • 2,814
  • 1
  • 24
  • 13
5

You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.

var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])
p8ul
  • 2,212
  • 19
  • 19
4

More "Try it Yourself" examples below.

Definition and Usage The split() method is used to split a string into an array of substrings, and returns the new array.

Tip: If an empty string ("") is used as the separator, the string is split between each character.

Note: The split() method does not change the original string.

var res = str.split(",");
HAROONMIND
  • 103
  • 7
2

Regexp

As more powerful alternative to split, you can use match

"0,1".match(/\d+/g)

let a = "0,1".match(/\d+/g)

console.log(a);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

var i = "[{a:1,b:2}]",
    j = i.replace(/([a-zA-Z0-9]+?):/g, '"$1":').replace(/'/g,'"'),
    k = JSON.parse(j);

console.log(k)

// => declaring regular expression

[a-zA-Z0-9] => match all a-z, A-Z, 0-9

(): => group all matched elements

$1 => replacement string refers to the first match group in the regex.

g => global flag

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
1

Split (",") can convert Strings with commas into a String array, here is my code snippet.

    var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
    var output = input.split(",");
    console.log(output);

["Hybrid App", " Phone-Gap", " Apache Cordova", " HTML5", " JavaScript", " BootStrap", " JQuery", " CSS3", " Android Wear API"]

Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
-1

Why don't you do replace , comma and split('') the string like this which will result into ['0', '1'], furthermore, you could wrap the result into parseInt() to transform element into integer type.

it('convert string to array', function () {
  expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});
Simple-Solution
  • 4,209
  • 12
  • 47
  • 66
-1

Example using Array.filter:

var str = 'a,b,hi,ma,n,yu';

var strArr = Array.prototype.filter.call(str, eachChar => eachChar !== ',');
montrealist
  • 5,593
  • 12
  • 46
  • 68
Abhimanyu
  • 104
  • 7