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:
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:
Call the “split()” method by passing “comma(,)” as an argument and store the result in a variable “array”:
Print the resultant array on the console using the “console.log()” method:
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:
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.