JavaScript - Convert Comma Separated String To Array Last Updated : 26 Nov, 2024 Comments Improve Suggest changes Like Article Like Report Here are the various methods to convert comma-separated string to array using JavaScript.1. Using the split() Method (Most Common)The split() method is the simplest and most commonly used way to convert a comma-separated string into an array. It splits a string into an array based on a specified character, such as a comma. JavaScript const s = "apple,banana,cherry"; const a = s.split(","); console.log(a); Output[ 'apple', 'banana', 'cherry' ] s.split(",") splits the string s wherever a comma appears.Returns an array of substrings.2. Using Array.prototype.reduce() MethodYou can use the reduce() method to build an array from a string for more control over the conversion process. JavaScript const s = "apple,banana,cherry"; const a = s.split("").reduce((obj, char) => { if (char === ",") { obj.push(""); } else { obj[obj.length - 1] += char; } return obj; }, [""]); console.log(a); Output[ 'apple', 'banana', 'cherry' ] The string is split into individual characters using s.split("").The reduce() function builds an array by concatenating characters until a comma is encountered.3. Using Loops and slice() MethodYou can manually process the string using loops and the slice() method to extract substrings. JavaScript const s = "apple,banana,cherry"; const a = []; let start = 0; for (let i = 0; i < s.length; i++) { if (s[i] === ",") { a.push(s.slice(start, i)); start = i + 1; } } a.push(s.slice(start)); console.log(a); Output[ 'apple', 'banana', 'cherry' ] The loop iterates through the string, finding commas.The slice() method extracts substrings between indexes and adds them to the array.4. Using Regular Expressions (RegExp) and match() MethodThe match() method, combined with a regular expression, is useful if the input string contains irregular spacing or special characters around the commas. JavaScript const s = "apple , banana , cherry "; const a = s.match(/[^,\s]+/g); console.log(a); Output[ 'apple', 'banana', 'cherry' ] [^,\s]+ matches sequences of characters that are not commas or spaces.The g flag ensures the regex matches all occurrences in the string.Handling Edge CasesWhen working with user-generated or inconsistent data, consider the following casesCase 1: Trailing CommasThe filter() method removes empty strings caused by trailing commas. JavaScript const s = "apple,banana,cherry,"; const a = s.split(",").filter(item => item !== ""); console.log(a); Output[ 'apple', 'banana', 'cherry' ] Case 2: Extra SpacesThe map() method trims unnecessary spaces from each substring. JavaScript const s = " apple , banana , cherry "; const a = s.split(",").map(item => item.trim()); console.log(a); Output[ 'apple', 'banana', 'cherry' ] Comparison of MethodsApproachUse CaseComplexitysplit()Ideal for clean, comma-separated strings without extra processing.O(n)reduce()Great for custom parsing logic or transformations.O(n)slice() + LoopsOffers low-level control but can be complicated.O(n)Regex + match()Best for handling irregular input with spaces or special characters.O(n)Edge Case HandlingNecessary for real-world scenarios like trailing commas and extra spaces.Depends on the case Comment More infoAdvertise with us Next Article JavaScript - Convert Comma Separated String To Array sayantanm19 Follow Improve Article Tags : JavaScript Web Technologies javascript-string javascript-array JavaScript-DSA +1 More Similar Reads Convert comma separated string to array in PySpark dataframe In this article, we will learn how to convert comma-separated string to array in pyspark dataframe. In pyspark SQL, the split() function converts the delimiter separated String to an Array. Â It is done by splitting the string based on delimiters like spaces, commas, and stack them into an array. Thi 3 min read JavaScript - Convert String to Array Strings in JavaScript are immutable (cannot be changed directly). However, arrays are mutable, allowing you to perform operations such as adding, removing, or modifying elements. Converting a string to an array makes it easier to:Access individual characters or substrings.Perform array operations su 5 min read How to convert a 2D array to a comma-separated values (CSV) string in JavaScript ? Given a 2D array, we have to convert it to a comma-separated values (CSV) string using JS. Input:[ [ "a" , "b"] , [ "c" ,"d" ] ]Output:"a,b c,d"Input:[ [ "1", "2"]["3", "4"]["5", "6"] ]Output:"1,23,45,6"To achieve this, we must know some array prototype functions which will be helpful in this regard 4 min read Convert Array to String in JavaScript In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen 7 min read Convert Lists to Comma-Separated Strings in Python Making a comma-separated string from a list of strings consists of combining the elements of the list into a single string with commas between each element. In this article, we will explore three different approaches to make a comma-separated string from a list of strings in Python. Make Comma-Separ 2 min read How to Convert String to Array of Objects JavaScript ? Given a string, the task is to convert the given string to an array of objects using JavaScript. It is a common task, especially when working with JSON data received from a server or API. Below are the methods that allow us to convert string to an array of objects:Table of ContentUsing JSON.parse() 4 min read How to Convert String of Objects to Array in JavaScript ? This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i 3 min read How to convert array of strings to array of numbers in JavaScript ? Converting an array of strings to an array of numbers in JavaScript involves transforming each string element into a numerical value. This process ensures that string representations of numbers become usable for mathematical operations, improving data handling and computational accuracy in applicati 4 min read Create a Comma Separated List from an Array in JavaScript Here are the different methods to create comma separated list from an Array1. Array join() methodThe Array join() method joins the elements of the array to form a string and returns the new string. The elements of the array will be separated by a specified separator. JavaScriptlet a = ["GFG1", "GFG2 3 min read JavaScript Array toString() Method The toString() method returns a string with array values separated by commas. The toString() method does not change the original array. This method converts an array into a readable string format, often for display or logging purposes.Syntax:arr.toString()Parameters: This method does not accept any 3 min read Like