How to convert comma separated string into an array in JavaScript?
Answer: Using spilt()
function
We can convert the comma-separated string into an array in JavaScript using split() method. This method splits the string into the array of substring and then returns a new array.
This method does not change the original string.
Example: Using split()
method
In the given example, we have used the split()
method to convert the comma-separated string into an array.
<!DOCTYPE html>
<html>
<head>
<title>Convert the comma-separated string into an array</title>
</head>
<body>
<script>
var str = 'HTML,CSS,JavaScript,PHP';
var result = str.split(',');
console.log(result);
</script>
</body>
</html>
Output
As we can see in the above example that a comma-separated string is converted into the array with the help of the split() method. But what if there is an empty field means there are two commas instead of one.
var str = 'HTML,CSS,,JavaScript,PHP';
So, if we want to treat these two commas as a field that is empty then we can do this easily with the help of split function.
Example
<script>
var str = 'HTML,,CSS,JavaScript,PHP';
var result = str.split(',');
console.log(result);
</script>
Output
As we can see in the output image that the second element of the array is an empty string.
The problem occurs when we do not want this empty field string in our array list. To remove these empty fields from the array we have to pass the regular expression within the split function for finding more than one comma in a sequence. This regular expression will treat all the commas within the string as a single comma.
Example: Split using regex
<script>
var str = 'HTML ,,,CSS ,JavaScript,PHP';
console.log(str.split(','));
var result = str.split(/,+/);
console.log(result);
</script>
Output
As we can see, in the first array all the commas except the first one are treated as an empty string while in the second array there is not an empty string. This is because the regular expression passed within the split() method treated all their commas as a single comma.
Removing white spaces
Generally, we use the trim() method to remove the white space from both sides of the string. We can also trim the white space using the split() method by just passing the regular expression as its parameter.
Example: Removing whitespaces
In the given example, we have removed the white space from both sides of the array element by just passing regular expression within the split() method.
<script>
var str = 'HTML ,,, CSS , JavaScript,PHP';
console.log(str.split(','));
var result = str.split(/\s*,+\s*/);
console.log(result);
</script>
Output
Conclusion
In this lesson, we have learned how to convert the comma-separated string into the array in JavaScript. JavaScript offers a predefined split() method with the help of which we can convert the comma-separated string into the array.