convert comma separated string into array in js

How to Convert Comma Separated String into JS Array

Often web developers need to convert comma separated string into JS array so that they can access individual elements of string easily, using indexes. There are several ways to do this in JavaScript. In this article, we will learn how to convert comma separated string into JS array.


How to Convert Comma Separated String into JS Array

Let us say you have the following JS string.

var fruits = 'apple, banana, cherry';

As you can see, it is a little difficult to access and work with string ‘banana’. So it is better to convert it into an array of strings where each fruit is an array item. You can do this easily using split() method, which splits a string into an array, based on a specific character, or substring.

We will use split() method to convert comma separated string into JS array as shown below. In split() method, you need to specify the character or substring using which your string needs to be split. We have specified comma ‘,’. Otherwise, it will split your string by whitespace characters.

var fruit_array = fruits.split(',');
console.log(fruit_array); // prints ['apple', 'banana', 'cherry']

Now you can easily access ‘banana’ as fruit_array[1] and work with it. If you want to reconvert the array items into a single string, you can do so using join() method.

Let us say we replace ‘banana’ with ‘orange’.

fruit_array[1] = 'orange';
console.log(fruit_array); // prints ['apple', 'orange', 'cherry']

Now we use join() function to convert it back into comma separated string. This approach makes it easy to modify specific parts of string in JavaScript.

var fruist2 = fruit_array.join();
console.log(fruits2); // returns 'apple, orange, cherry'

In fact, you can use the split() method to split string by any character, or substring. For example, let us say if you have a tab delimited string, instead of comma separated string.

var fruits = 'apple, banana, cherry';

We can split this string into an array by calling split() method without mentioning any argument.

var fruit_array = fruits.split();

In this article, we have learnt how to convert comma separated string into JS array. You can customize it as per your requirement.

Also read:

How to Suppress Warning Messages in MySQL
How to Show JavaScript Date in AM/PM Format
How to Get HTML Element’s Actual Width & Height
How to Call Parent Window Function from IFrame
How to Get Cookie By Name in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *