Javascript split string to array by comma

Topic: JavaScript / jQueryPrev|Next

Answer: Use the split() Method

You can use the JavaScript split() method to split a string using a specific separator such as comma (,), space, etc. If separator is an empty string, the string is converted to an array of characters.

The following example demonstrates how to convert a comma separated string of person name into an array and retrieve the individual name using JavaScript.

Please check out the tutorial on JavaScript Strings to learn more about string manipulation.


Here are some more FAQ related to this topic:

  • How to check if a value exists in an array in JavaScript
  • How to remove duplicate values from a JavaScript array
  • How to display all items or values in an array using loop in jQuery

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

MDN reference, mostly helpful for the possibly unexpected behavior of the limit parameter. (Hint: "a,b,c".split(",", 2) comes out to ["a", "b"], not ["a", "b,c"].)

answered May 18, 2010 at 14:24

10

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.

Javascript split string to array by comma

answered Dec 14, 2010 at 15:58

poppop

3,1242 gold badges23 silver badges41 bronze badges

11

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);

Javascript split string to array by comma

answered Aug 29, 2012 at 15:12

JustmeJustme

3713 silver badges3 bronze badges

2

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

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

om-nom-nom

61.9k13 gold badges181 silver badges225 bronze badges

answered May 18, 2010 at 14:27

JakkwyldeJakkwylde

1,2969 silver badges16 bronze badges

3

Note that the following:

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

will alert 1

Javascript split string to array by comma

answered Mar 18, 2014 at 14:16

user1386213user1386213

8519 silver badges16 bronze badges

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;
}

Javascript split string to array by comma

answered Nov 29, 2012 at 9:51

Javascript split string to array by comma

BJ PatelBJ Patel

6,09811 gold badges46 silver badges81 bronze badges

4

Upgraded str.split(',')

The simple str.split(',') doesn't have much smarts. Here are some upgrades for different needs. You can customize the functionality to your heart's content.

const str = "a, b,c,  d  ,e  ,f,,g"
const num = "1, 2,3,  4  ,5  ,6,,7.495"
const mix = "a, 2,3,  d  ,5  ,f,,7.495,g"

console.log(    str.split(',')
) // spaces NOT trimmed, empty values included
  // ["a", " b", "c", "  d  ", "e  ", "f", "", "g"] 

console.log(    str.split(/[ ,]+/)
) // spaces trimmed, empty values skipped
  // ["a", "b", "c", "d", "e", "f", "g"] 

console.log(    str.split(/\s*,\s*/)
) // spaces trimmed, empty values NOT skipped
  // ["a", "b", "c", "d", "e", "f", "", "g"]

console.log(    num.split(',').map(Number)
) // numbers, empty values default to zero
  // [1, 2, 3, 4, 5, 6, 0, 7.495] 

console.log(    num.split(/[ ,]+/).map(Number)
) // numbers, skips empty values
  // [1, 2, 3, 4, 5, 6, 7.495]

console.log(    mix.split(/\s*,\s*/)
                .map(x => (x === '') ? '' : (isNaN(Number(x)) ? x : Number(x)) )
) // mixed values, empty values included
  // ["a", 2, 3, "d", 5, "f", "", 7.495, "g"]

Using JSON.parse

It may feel like a bit of a hack, but it's simple and highly optimized by most Javascript engines.

It has some other advantages such as support for nested lists. But there are disadvantages, such as requiring the input to be properly formatted JSON.

By using string.replace similar to how I used string.split above, you can fix the input. In the first two examples below, I customize how I want empty values handled:

const num = "1, 2,3,  4  ,5  ,6,,7.495"
const mix = "a, 2,3,  d  ,5  ,f,7.495,g"

console.log(    JSON.parse('['+num.replace(/,\s*,/,',0,')+']')
) // numbers, empty values default to zero
  // [1, 2, 3, 4, 5, 6, 0, 7.495]

console.log(    JSON.parse('['+num.replace(/,\s*,/,',')+']')
) // numbers, skips empty values
  // [1, 2, 3, 4, 5, 6, 7.495]

console.log(    JSON.parse('['+mix.replace(/(^|,)\s*([^,]*[^0-9, ][^,]*?)\s*(?=,|$)/g,'$1"$2"')+']') 
) // mixed values, will ERROR on empty values
  // ["a", 2, 3, "d", 5, "f", "7.495", "g"]  

answered Nov 14, 2021 at 18:51

Javascript split string to array by comma

InigoInigo

8,6964 gold badges31 silver badges59 bronze badges

0

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) {
      fullArray.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).

Javascript split string to array by comma

radu122

2,77622 silver badges24 bronze badges

answered Oct 22, 2013 at 16:23

Kabb5Kabb5

3,6622 gold badges32 silver badges55 bronze badges

2

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(',')

Javascript split string to array by comma

Mosbah

1,5171 gold badge14 silver badges27 bronze badges

answered Jan 23, 2019 at 9:18

Javascript split string to array by comma

Mubeen KhanMubeen Khan

8971 gold badge10 silver badges11 bronze badges

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/

Javascript split string to array by comma

answered Sep 18, 2015 at 16:48

Javascript split string to array by comma

Andi ARAndi AR

2,5182 gold badges22 silver badges28 bronze badges

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.

Javascript split string to array by comma

answered Jun 18, 2015 at 3:58

Diego PamioDiego Pamio

1,37911 silver badges21 bronze badges

A good solution for that:

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

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

Javascript split string to array by comma

answered Mar 21, 2018 at 13:59

ManspofManspof

1,30523 gold badges73 silver badges163 bronze badges

answered Oct 21, 2019 at 19:17

Javascript split string to array by comma

Kamil KiełczewskiKamil Kiełczewski

75.9k26 gold badges335 silver badges313 bronze badges

2

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')

Javascript split string to array by comma

answered Jun 23, 2020 at 9:53

Javascript split string to array by comma

I made php script to convert string to array, and you can run it into your browser, so is easy


"; } ?>

answered May 2, 2021 at 6:22

Javascript split string to array by comma

let myString = "January,February,March,April,May,June,July,August,September,October,November,December";
      const temp=myString .split(",");
      console.log(temp);

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

Very simple you can use the split default javascript function for this.

answered May 8, 2021 at 11:55

Javascript split string to array by comma

Force BoltForce Bolt

1,0098 silver badges7 bronze badges

If the user makes a typo by adding an extra space. You could use something like this.

tags: foo,  zar, gar
const stringToArr = (string) => {
  return string.trim.split(",");
};

answered Aug 19, 2021 at 15:02

Javascript split string to array by comma

0

Easiest way to do it:

let myStr = '1, 2, 3, 4, 5, 7, 8';

const stringToArr = (myStr) => {
    return myStr.split(',').map(x => x.trim());
};

answered Jun 29 at 7:44

Javascript split string to array by comma

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

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

Javascript split string to array by comma

answered Nov 20, 2019 at 7:25

Javascript split string to array by comma

Srikanth GowdaSrikanth Gowda

5,4737 gold badges18 silver badges33 bronze badges

4

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string by a comma and space?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.

Which method can you use character other than comma to separate values from array?

In that case, the split() method returns an array with the entire string as an element. In the example below, the message string doesn't have a comma (,) character.

How Split comma separated Values in HTML?

To convert comma separated text into separate lines, you need to use trim() along with split() on the basis of comma(,).