Split Space Delimited String and Trim Extra Commas and Spaces in JavaScript?

When working with strings that contain multiple commas and spaces, you can use regular expressions with split() and join() methods to clean them up effectively.

The Problem

Consider this messy string with multiple consecutive commas and spaces:

var sentence = "My,,,,,,, Name,,,, is John ,,, Smith";
console.log("Original string:", sentence);
Original string: My,,,,,,, Name,,,, is John ,,, Smith

Solution: Using Regular Expression with split() and join()

The split(/[\s,]+/) method splits the string on one or more spaces or commas, while join() reassembles it with clean separators:

var sentence = "My,,,,,,, Name,,,, is John ,,, Smith";
console.log("Before cleaning:", sentence);

// Split on multiple spaces/commas and join with single comma
sentence = sentence.split(/[\s,]+/).join(',');
console.log("After cleaning:", sentence);
Before cleaning: My,,,,,,, Name,,,, is John ,,, Smith
After cleaning: My,Name,is,John,Smith

How It Works

The regular expression /[\s,]+/ breaks down as:

  • [\s,] - Matches any whitespace character or comma
  • + - Matches one or more consecutive occurrences

The join() method without arguments uses comma as default separator.

Alternative: Join with Spaces

You can also join the cleaned parts with spaces instead of commas:

var sentence = "My,,,,,,, Name,,,, is John ,,, Smith";
console.log("Original:", sentence);

// Join with spaces instead of commas
var cleanSentence = sentence.split(/[\s,]+/).join(' ');
console.log("Cleaned with spaces:", cleanSentence);
Original: My,,,,,,, Name,,,, is John ,,, Smith
Cleaned with spaces: My Name is John Smith

Handling Edge Cases

The method also handles strings that start or end with separators:

var messyString = ",,,  Hello  ,,,  World  ,,,";
console.log("Messy string:", messyString);

var cleaned = messyString.split(/[\s,]+/).filter(word => word.length > 0).join(' ');
console.log("Cleaned string:", cleaned);
Messy string: ,,,  Hello  ,,,  World  ,,,
Cleaned string: Hello World

Conclusion

Using split(/[\s,]+/).join() is an efficient way to remove multiple consecutive commas and spaces from strings. The regular expression handles any combination of whitespace and commas, making your data clean and consistent.

Updated on: 2026-03-15T23:18:59+05:30

440 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements