JavaScript

JavaScript Split String Into Array by Comma

The string is a collection of characters representing a single data and separated using separators such as commas, spaces, and so on. While coding, the programmers sometimes need to change a string into an array. JavaScript offers several methods to convert a string into an array, but the conversion of the string based on the separator is done by using the “split()” method.

This post will demonstrate the procedure to split a string into an array by a comma in JavaScript.

How to Split String Into an Array by Comma in JavaScript?

The “split()” method uses a separator to split a String into an ordered sequence of substrings. The array containing these substrings is then returned. It doesn’t change the original string in any way.

Syntax
Follow the given-provided syntax for the split() method:

string.split(',')

Here, comma (,) is the separator where the string will split.

Return Value
It returns an array of split strings.

Example 1:
Create a variable “string” that stores a comma-separated string:

var string = "Linuxhint, best Website, learning, Skills";

Call the “split()” method by passing “comma(,)” as an argument and store the result in a variable “array”:

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

Print the resultant array on the console using the “console.log()” method:

console.log(array);

Output

The above output shows that the string splits into an array whenever a comma is encountered.

Example 2
In the following example, get the value of the splitted string at the specified index of the array:

console.log(array[2]);

Output

This blog has provided the necessary information related to the split() method to split the string into an array by comma.

Conclusion

The “split()” method can be utilized to split a string into an array by comma. The split() method splits the string into substrings based on the specified separator and gives back an array of the split substrings as an output. The specified separator is passed inside the arguments of the split method, which in the given case will be a “comma”. This post demonstrated the procedure to split the string into an array by a comma 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.