Trim and split string to form array in JavaScript

When working with comma-separated strings that contain unwanted whitespace, you need to trim spaces and split the string into an array. JavaScript provides multiple approaches to accomplish this task efficiently.

Problem Statement

Given a comma-separated string with irregular spacing:

const str = "a, b, c, d , e";
console.log("Original string:", str);
Original string: a, b, c, d , e

We need to remove all whitespaces and split it into a clean array of elements.

Method 1: Manual Space Removal

This approach manually loops through the string to remove spaces before splitting:

const str = "a, b, c, d , e";

const shedAndSplit = (str = '') => {
    const removeSpaces = () => {
        let res = '';
        for(let i = 0; i < str.length; i++){
            const el = str[i];
            if(el === ' '){
                continue;
            };
            res += el;
        };
        return res;
    };
    const res = removeSpaces();
    return res.split(',');
};

console.log(shedAndSplit(str));
[ 'a', 'b', 'c', 'd', 'e' ]

Method 2: Using replace() and split() (Recommended)

A more concise approach using built-in string methods:

const str = "a, b, c, d , e";

const trimAndSplit = (str = '') => {
    return str.replace(/\s+/g, '').split(',');
};

console.log(trimAndSplit(str));
[ 'a', 'b', 'c', 'd', 'e' ]

Method 3: Split First, Then Trim Each Element

This approach splits first and trims each individual element:

const str = "a, b, c, d , e";

const splitAndTrim = (str = '') => {
    return str.split(',').map(item => item.trim());
};

console.log(splitAndTrim(str));
[ 'a', 'b', 'c', 'd', 'e' ]

Comparison

Method Performance Readability Best For
Manual Loop Fast Low Learning purposes
replace() + split() Good High Removing all spaces
split() + map(trim) Good High Preserving inner spaces

Handling Edge Cases

Here's a robust function that handles empty strings and extra commas:

const robustTrimSplit = (str = '') => {
    if (!str.trim()) return [];
    return str.split(',')
              .map(item => item.trim())
              .filter(item => item !== '');
};

console.log(robustTrimSplit("a, , b, c,  , d"));
console.log(robustTrimSplit(""));
[ 'a', 'b', 'c', 'd' ]
[]

Conclusion

For most use cases, split(',').map(item => item.trim()) provides the best balance of readability and functionality. Use replace(/\s+/g, '').split(',') when you need to remove all whitespace completely.

Updated on: 2026-03-15T23:19:00+05:30

909 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements