Convert string with commas to array
Solution 1
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);
Solution 2
Split it on the ,
character;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
Solution 3
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.
Solution 4
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);
Solution 5
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
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"}"]
Scott
Updated on August 26, 2020Comments
-
Scott almost 4 years
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
would pop-up a0,1
. When it would be an array, it would pop-up a0
, and whenalert(array[1]);
is called, it should pop-up the1
.Is there any chance to convert such string into a JavaScript array?
-
scunliffe over 11 yearsAlso be aware that
JSON.parse();
is not available in IE6, IE7. I think in this case theString.split(',');
is easier. -
I Hate Lazy over 11 years@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 over 11 years@Downvoter: Try to describe what is wrong with the answer so that I can demonstrate how you're wrong.
-
Andi AR almost 9 years@I Hate Lazy This doesnt support object string.see here stackoverflow.com/a/32657055/2632619
-
WestCoastProjects over 8 yearsThis is the most generally applicable answer. JSON can not be used for arbitrary delimiters (e.g. tab, space, etc)
-
Wilt about 8 years@FarzadYZ Be careful with that (using
eval
). If the array contains values from client side input this will be insecure. -
Wilt about 8 yearsThis 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). -
Farzad Yousefzadeh about 8 years@Wilt Actually
eval
is always a security concern -
Onur Yıldırım almost 8 yearsDon't use
JSON.parse
approach, it's never wise to form and evaluate strings into JS. Usesplit
+map
, it's better and elegant. -
Eshwar Prasad Yaddanapudi almost 8 years
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 didassert
using_.isArray(JSON.parse(receivedValue))
-
Eshwar Prasad Yaddanapudi almost 8 yearsThis is awesome. I moved my code from
JSON.parse
toArray.from
as am usingES6
. Thank youRay Kim
-
Janatbek Orozaly over 7 yearsconsole.log(typeof Data); //string ========== var myArray = Array.from(Data); ============ console.log(typeof myArray); //Object doesn't support property or method 'from' ========== Why Is that?
-
29er about 7 yearsThis is NOT supported in any version of IE. be careful
-
Artyom Pranovich about 7 yearsAwesome! Along with Array.from answer they should be the only answers for ES6 solutions.
-
Tina Chen about 7 yearsBut
Array.from("0, 1, 233")
will return["0", ",", " ", "1", ",", " ", "2", "3", "3"]
, what if I want[0, 1, 233]
? -
Admin almost 7 years
string.split(',');
ORfor of & push
-
Admin almost 7 yearsbad solution! more info seeing
https://github.com/gildata/RAIO/issues/116#issuecomment-325901359
-
Admin almost 7 yearsbad solution! more info seeing
https://github.com/gildata/RAIO/issues/116#issuecomment-325901359
-
sqp_125 almost 7 yearsGreat function I also use it but unfortunately it does NOT work for strings or symbols: like e.g. "0,s" any ideas how to fix that?
-
Edison D'souza almost 7 yearsThis 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.
-
Unreality over 6 years@sqp_125 try 0,'s' ?
-
Dan Mantyla over 6 years@Wilt well no it wouldn't, but yeah you could use regex to fix that
-
Wilt over 6 yearsI 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.
-
Arnav Borborah over 6 yearsIs there a syntax for converting a comma separated string into a number array using es6 features?
-
pldg almost 6 yearsThere is an error in this answer.
"0,1".split()
returns["0,1"]
and not["0", "1"]
. Use"0,1".split(",")
to return["0", "1"]
-
vhs over 4 yearsThis method is only reliable when argument is a
Set
of strings. -
xgqfrms over 2 yearsthis solution not work any more
-
ya.teck about 2 yearsCould be shortened as follows
string.split(',').map(Number)