JavaScript

Convert String With Commas to Array

A string is often regarded as a data type and is frequently implemented as an array data structure composed of bytes (or words) that uses character encoding to hold a sequence of components, typically characters. Programmers often need to convert the comma-separated strings to an array. To do this, JavaScript gives a predefined method called the split() method.

This article will describe the procedure for converting the string with a comma to an array in JavaScript.

How to Convert String With Commas to Array?

For converting string with commas to an array, use the “split()” method. It is used to split a text based on any separator and convert it into an array of substrings and return a new array.

Syntax
Use the given syntax to convert a string with commas to an array:

split(separator)

Here, the separator is comma “,”.

Example
Create a comma-separated string:

var string = "Monday, Tuesday, Thursday, Friday, Saturday, Sunday";

Invoke the split() method by passing a comma as a separator:

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

Finally, print the array on substrings on the console:

console.log(array);

The output indicates that the comma-separated string has been successfully converted to an array:

When the split() method is used on an empty string, it produces an array containing an empty string rather than an empty array:

If you want to retrieve an empty array when the string is empty, you can add a filter() function after the split method:

That’s all about the conversion of a string with commas to an array.

Conclusion

To the conversion of string with commas to an array, utilize the “split()” method. It is used to split a text based on any separator and convert it into an array of substrings and return a new array. If the string is empty, use the filter() method to get an empty array, while the split() method gives an array of empty strings. This article described the procedure for converting the string with commas to an array in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.