[javascript] How can I convert a comma-separated string to an array?

I have a comma-separated string that I want to convert into an array, so I can loop through it.

Is there anything built-in to do this?

For example, I have this string

var str = "January,February,March,April,May,June,July,August,September,October,November,December";

Now I want to split this by the comma, and then store it in an array.

This question is related to javascript string split

The answer is


Hmm, split is dangerous IMHO as a string can always contain a comma. Observe the following:

var myArr = "a,b,c,d,e,f,g,','";
result = myArr.split(',');

So how would you interpret that? And what do you want the result to be? An array with:

['a', 'b', 'c', 'd', 'e', 'f', 'g', '\'', '\''] or
['a', 'b', 'c', 'd', 'e', 'f', 'g', ',']

Even if you escape the comma, you'd have a problem.

I quickly fiddled this together:

(function($) {
    $.extend({
        splitAttrString: function(theStr) {
            var attrs = [];

            var RefString = function(s) {
                this.value = s;
            };
            RefString.prototype.toString = function() {
                return this.value;
            };
            RefString.prototype.charAt = String.prototype.charAt;
            var data = new RefString(theStr);

            var getBlock = function(endChr, restString) {
                var block = '';
                var currChr = '';
                while ((currChr != endChr) && (restString.value !== '')) {
                    if (/'|"/.test(currChr)) {
                        block = $.trim(block) + getBlock(currChr, restString);
                    }
                    else if (/\{/.test(currChr)) {
                        block = $.trim(block) + getBlock('}', restString);
                    }
                    else if (/\[/.test(currChr)) {
                        block = $.trim(block) + getBlock(']', restString);
                    }
                    else {
                        block += currChr;
                    }
                    currChr = restString.charAt(0);
                    restString.value = restString.value.slice(1);
                }
                return $.trim(block);
            };

            do {
                var attr = getBlock(',', data);
                attrs.push(attr);
            }
            while (data.value !== '')
                ;
            return attrs;
        }
    });
})(jQuery);

A good solution for that:

let obj = ['A','B','C']

obj.map((c) => { return c. }).join(', ')

For an array of strings to a comma-separated string:

let months = ["January","Feb"];
let monthsString = months.join(", ");

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

var array = string.split(',');

Here is a function that will convert a string to an array, even if there is only one item in the list (no separator character):

function listToAray(fullString, separator) {
  var fullArray = [];

  if (fullString !== undefined) {
    if (fullString.indexOf(separator) == -1) {
      fullAray.push(fullString);
    } else {
      fullArray = fullString.split(separator);
    }
  }

  return fullArray;
}

Use it like this:

var myString = 'alpha,bravo,charlie,delta';
var myArray = listToArray(myString, ',');
myArray[2]; // charlie

var yourString = 'echo';
var yourArray = listToArray(yourString, ',');
yourArray[0]; // echo

I created this function because split throws out an error if there isn't any separator character in the string (only one item).


Pass your comma-separated string into this function and it will return an array, and if a comma-separated string is not found then it will return null.

function splitTheString(CommaSepStr) {
    var ResultArray = null;

    // Check if the string is null or so.
    if (CommaSepStr!= null) {

        var SplitChars = ',';

        // Check if the string has comma of not will go to else
        if (CommaSepStr.indexOf(SplitChars) >= 0) {
            ResultArray = CommaSepStr.split(SplitChars);

        }
        else {

            // The string has only one value, and we can also check
            // the length of the string or time and cross-check too.
            ResultArray = [CommaSepStr];
        }
    }
    return ResultArray;
}

As @oportocala mentions, an empty string will not result in the expected empty array.

So to counter, do:

str
.split(',')
.map(entry => entry.trim())
.filter(entry => entry)

For an array of expected integers, do:

str
.split(',')
.map(entry => parseInt(entry))
.filter(entry => typeof entry ==='number')

You can try the following snippet:

 var str = "How,are,you,doing,today?";
    var res = str.split(",");
    console.log("My Result:", res)

Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");

Adding a loop like this,

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

will return an array containing integers, and not strings.


Return function

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

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/


Note that the following:

var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);

will alert 1


I had a similar issue, but more complex as I needed to transform a CSV file into an array of arrays (each line is one array element that inside has an array of items split by comma).

The easiest solution (and more secure I bet) was to use PapaParse which has a "no-header" option that transform the CSV file into an array of arrays, plus, it automatically detected the "," as my delimiter.

Plus, it is registered in Bower, so I only had to:

bower install papa-parse --save

And then use it in my code as follows:

var arrayOfArrays = Papa.parse(csvStringWithEnters), {header:false}).data;

I really liked it.


let str = "January,February,March,April,May,June,July,August,September,October,November,December"

let arr = str.split(',');

it will result:

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

and if you want to convert following to:

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

this:

"January,February,March,April,May,June,July,August,September,October,November,December";

use:

str = arr.join(',')

Shortest

str.split`,`

_x000D_
_x000D_
var str = "January,February,March,April,May,June,July,August,September,October,November,December";_x000D_
_x000D_
let arr = str.split`,`;_x000D_
_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows