Convert Comma Separated String to Array in JavaScript

Use the split() method.



Let’s say we’ve got the list with some names.

There are many of them, and we have to do some operations on them. In this case, we should convert them to the array at first.

Thankfully it’s very easy. All we have to do is to use the split() method with a comma as a separator on our string.

Remember: If there is a space after a comma, you should include it in your code. In these scenarios, your split(“,”) should look like split(“, “) (with extra space after a comma).

    var names = 'Elizabeth, Robert, Kevin, Tom, Erin, Zack, Josh';
    var arrayWithNames = names.split(", ");


Output (console): (7) [‘Elizabeth’, ‘Robert’, ‘Kevin’, ‘Tom’, ‘Erin’, ‘Zack’, ‘Josh’]