JavaScript – Convert Comma-Separated String into Array

To convert a comma separated string into an array in JavaScript, call split() method on this comma-separated string and pass comma character as first argument which acts as separator.

Syntax

The syntax to split a comma separated string str into an array is

</>
Copy
str.split(',')

Examples

In the following example, we take a comma separated string str and split this string with comma character as separator using split() method. split() returns an array.

We shall display the elements of the array to html output.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var str = 'apple,banana,mango,orange';
        var separator = ',';

        var resultArr = str.split(separator);

        var output = '';
        output += 'CSV String : ' + str;
        output += '\n\nOutput Array : \n'
        resultArr.forEach(function printing(element, index, resultArr){
            output += element + '\n';
        });
        document.getElementById('output').innerHTML = output;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to split a comma separated string into an array of values in JavaScript, using split() method, with examples.