Split a String by Space or Comma using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Split a String by Space or Comma using JavaScript #

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/. The method will split the string on each occurrence of a space or comma and return an array containing the substrings.

index.js
const str = 'one two, three'; const result = str.split(/[, ]+/); console.log(result); // 👉️ ['one', 'two', 'three']

The only parameter we passed to the String.split method is a regular expression that serves as a separator.

The forward slashes / / mark the beginning and end of the regular expression.

The square brackets [] are called a character class and match any of the characters between the brackets, in our case - each comma and space.

The plus + matches the preceding item (comma or space) one or more times. This means that if you had a comma and a space one after another, they would count as a single match.

Here's an example:

index.js
const str = 'one two,,,, three'; const result = str.split(/[, ]+/); console.log(result); // 👉️ ['one', 'two', 'three']

Even though we have multiple spaces and commas one after another, the plus + character considers them to be a single match.

If you need a regex cheatsheet, check out this one from MDN.

There might be an edge case that you need to handle - if the string ends in a comma or space, you'd get an empty string element at the end of the array.
index.js
const str = 'one two, three,'; const result = str.split(/[, ]+/); // 👇️ ['one', 'two', 'three', ''] console.log(result);

The split method splits on each occurrence of a comma or space, however there's nothing after the last comma, so we get an empty string.

You can use the Array.filter method to filter out any empty strings from the array.

index.js
const str = 'one two, three,'; const result = str.split(/[, ]+/).filter(element => element); // 👇️ ['one', 'two', 'three'] console.log(result);

The function we passed to the filter() method gets called with each element in the array.

On each iteration, we simply return the element as is.

The filter method returns a new array containing only the elements for which the callback function returned a truthy value.

Truthy are all the values that are not falsy.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

If the element is an empty string and we return it from the callback function, it won't get added to the new array because an empty string is a falsy value.

Alternatively, you could shorten this further, by passing the Boolean object to the filter method.

index.js
const str = 'one two, three,'; const result = str.split(/[, ]+/).filter(Boolean); // 👇️ ['one', 'two', 'three'] console.log(result);

The Boolean object takes a value as a parameter, converts it to its boolean representation and returns the result.

index.js
console.log(Boolean('hello')); // 👉️ true console.log(Boolean('')); // 👉️ false

We know that empty strings are falsy values, so when converted to boolean, they evaluate to false and don't get included in the new array.

Which approach you pick is a matter of personal preference. I'd go with returning the element, as I find the Boolean object approach to be a bit more implicit.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.