Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - Convert Comma Separated String To Array
Next article icon

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() Method

You 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() Method

You 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() Method

The 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 Cases

When working with user-generated or inconsistent data, consider the following cases

Case 1: Trailing Commas

The 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 Spaces

The 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 Methods

ApproachUse CaseComplexity
split()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

Next Article
JavaScript - Convert Comma Separated String To Array

S

sayantanm19
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • javascript-array
  • JavaScript-DSA

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences