Convert string with commas to array

1,196,945

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

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:
1,196,945
Scott
Author by

Scott

Updated on August 26, 2020

Comments

  • Scott
    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 a 0,1. When it would be an array, it would pop-up a 0, and when alert(array[1]); is called, it should pop-up the 1.

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

  • scunliffe
    scunliffe over 11 years
    Also be aware that JSON.parse(); is not available in IE6, IE7. I think in this case the String.split(','); is easier.
  • I Hate Lazy
    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
    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
    Andi AR almost 9 years
    @I Hate Lazy This doesnt support object string.see here stackoverflow.com/a/32657055/2632619
  • WestCoastProjects
    WestCoastProjects over 8 years
    This is the most generally applicable answer. JSON can not be used for arbitrary delimiters (e.g. tab, space, etc)
  • Wilt
    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
    Wilt about 8 years
    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).
  • Farzad Yousefzadeh
    Farzad Yousefzadeh about 8 years
    @Wilt Actually eval is always a security concern
  • Onur Yıldırım
    Onur Yıldırım almost 8 years
    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.
  • Eshwar Prasad Yaddanapudi
    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 did assert using _.isArray(JSON.parse(receivedValue))
  • Eshwar Prasad Yaddanapudi
    Eshwar Prasad Yaddanapudi almost 8 years
    This is awesome. I moved my code from JSON.parse to Array.from as am using ES6. Thank you Ray Kim
  • Janatbek Orozaly
    Janatbek Orozaly over 7 years
    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?
  • 29er
    29er about 7 years
    This is NOT supported in any version of IE. be careful
  • Artyom Pranovich
    Artyom Pranovich about 7 years
    Awesome! Along with Array.from answer they should be the only answers for ES6 solutions.
  • Tina Chen
    Tina Chen about 7 years
    But Array.from("0, 1, 233") will return ["0", ",", " ", "1", ",", " ", "2", "3", "3"], what if I want [0, 1, 233] ?
  • Admin
    Admin almost 7 years
    string.split(','); OR for of & push
  • Admin
    Admin almost 7 years
    bad solution! more info seeing https://github.com/gildata/RAIO/issues/116#issuecomment-3259‌​01359
  • Admin
    Admin almost 7 years
    bad solution! more info seeing https://github.com/gildata/RAIO/issues/116#issuecomment-3259‌​01359
  • sqp_125
    sqp_125 almost 7 years
    Great 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
    Edison D'souza almost 7 years
    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.
  • Unreality
    Unreality over 6 years
    @sqp_125 try 0,'s' ?
  • Dan Mantyla
    Dan Mantyla over 6 years
    @Wilt well no it wouldn't, but yeah you could use regex to fix that
  • Wilt
    Wilt over 6 years
    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.
  • Arnav Borborah
    Arnav Borborah over 6 years
    Is there a syntax for converting a comma separated string into a number array using es6 features?
  • pldg
    pldg almost 6 years
    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"]
  • vhs
    vhs over 4 years
    This method is only reliable when argument is a Set of strings.
  • xgqfrms
    xgqfrms over 2 years
    this solution not work any more
  • ya.teck
    ya.teck about 2 years
    Could be shortened as follows string.split(',').map(Number)