How to Split a string by Spaces in JavaScript

avatar
Borislav Hadzhiev

Last updated: Jan 9, 2023
9 min

banner

# Table of Contents

  1. Split a string by Space in JavaScript
  2. Split a String by Multiple Spaces in JavaScript
  3. Split a String keeping the Whitespace in JavaScript
  4. Split String and remove surrounding Spaces in JavaScript
  5. Split a String by Space or Comma using JavaScript

# Split a string by Space in JavaScript

Use the split() method to split a string by a space.

The method will split the string on each occurrence of a space returning an array of the results.

index.js
const str = 'bobby hadz com'; const arr = str.split(' '); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(arr);

split string by space

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

The only argument we passed to the String.split() method is the separator on which we want to split the string.

index.js
// ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz' ] console.log('bobby hadz'.split(' ')); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz' ] console.log('bobby-hadz'.split('-'));

# Split a String by Multiple Spaces in JavaScript

Call the split() method with a regular expression to split a string by multiple spaces.

The regular expression will split the string by one or more spaces and will return an array containing the results.

index.js
const str = ' bobby hadz com '; const arr = str.trim().split(/\s+/); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

split string by multiple spaces

The String.trim() method removes the leading and trailing whitespace from a string and returns a new string, without modifying the original string.

index.js
console.log(' a '.trim()); // ๐Ÿ‘‰๏ธ "a"

We have to remove the leading and trailing spaces because we'd get empty string elements if the string starts or ends with a space.

index.js
const str = ' bobby hadz com '; // ๐Ÿ‘‡๏ธ [ '', 'bobby', 'hadz', 'com', '' ] console.log(str.split(/\s+/));

We called the String.split() method with a regular expression.

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

The \s special character matches any whitespace (spaces, tabs or newlines).

The plus + matches the preceding item (the space) one or more times. In other words, the plus matches one or more spaces, treating them as a single match.

This approach would also work if you need to split the string on multiple whitespace characters.

index.js
const str = ' banana \n \t kiwi \r\n mango '; const result = str.trim().split(/\s+/); console.log(result); // ๐Ÿ‘‰๏ธ ['banana', 'kiwi', 'mango']

The \s special character matches any whitespace including spaces, tabs and newlines.

If you have to do this often, define a reusable function.

index.js
function splitMultipleSpaces(str) { return str.trim().split(/\s+/); } const str = ' bobby hadz com '; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(splitMultipleSpaces(str));

The function takes a string as a parameter and splits the string by one or more consecutive spaces.

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

# Split a String keeping the Whitespace in JavaScript

You can use the split() method with a regex to split a string, keeping the whitespace.

index.js
const str = 'bobby hadz com'; const arr = str.split(/(\s+)/); // ๐Ÿ‘‡๏ธ [ 'bobby', ' ', 'hadz', ' ', 'com' ] console.log(arr);

split string keeping the whitespace

The regular expression uses a capturing group to preserve the whitespace when splitting the string.

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

We passed a regular expression to the String.split() method.

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

The \s special character matches whitespace (spaces, tabs, newlines).

The plus + matches the preceding item (whitespace) one or more times, in other words it would collapse multiple consecutive spaces into 1.

The parentheses () are called a capturing group and allow us to match the character and still include it in the results.

Here's an easy way to visualize how capturing groups work.

index.js
console.log('abc'.split(/b/)); // ๐Ÿ‘‰๏ธ ['a', 'c'] console.log('abc'.split(/(b)/)); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c']

The second example uses a capturing group () to match the b character, but still includes it in the result.

If you have to do this often, define a reusable function.

index.js
function splitKeepingWhitespace(str) { return str.split(/(\s+)/); } const str = 'bobby hadz com'; const arr = splitKeepingWhitespace(str); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', ' ', 'hadz', ' ', 'com' ]

The function takes a string as a parameter, splits it and keeps the whitespace.

# Split a String keeping the Whitespace using split() and join()

This is a three-step process:

  1. Use the split() method to split the string on each space.
  2. Use the join() method to join the array into a string.
  3. Use the split() method to split the string and keep the whitespace.
index.js
const str = 'bobby hadz com'; const result = str.split(' ').join('# #').split('#'); console.log(result); // ๐Ÿ‘‰๏ธ [ 'bobby', ' ', 'hadz', ' ', 'com' ]

split string keeping the whitespace using split and join

We first split the string on each space to get an array containing the words in the string.

index.js
const str = 'bobby hadz com'; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(str.split(' '));

The next step is to convert the array to a string, by using the join() method.

index.js
const str = 'bobby hadz com'; // ๐Ÿ‘‡๏ธ bobby# #hadz# #com console.log(str.split(' ').join('# #'));

We used a hash #, however, we could have used any other character, as long as there is a space in the middle.

The last step is to split the string on each hash.

index.js
const str = 'bobby hadz com'; const result = str.split(' ').join('# #').split('#'); console.log(result); // ๐Ÿ‘‰๏ธ [ 'bobby', ' ', 'hadz', ' ', 'com' ]

If you have to do this often, define a reusable function.

index.js
function splitKeepingWhitespace(str) { return str.split(' ').join('# #').split('#'); } const str = 'bobby hadz com'; const arr = splitKeepingWhitespace(str); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', ' ', 'hadz', ' ', 'com' ]

The function takes a string as a parameter, splits the string and preserves the whitespace.

# Split String and remove surrounding Spaces in JavaScript

To split a string and trim the surrounding spaces:

  1. Use the split() method to split the string into an array.
  2. Use the map() method to iterate over the array.
  3. Use the trim() method on the string to remove the surrounding spaces.
index.js
const str = 'bobby - hadz - com'; const arr = str.split('-') .map(element => element.trim()); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

The only argument we passed to the split() method is the separator by which we want to split the string.

index.js
const str = 'bobby - hadz - com'; // ๐Ÿ‘‡๏ธ [ 'bobby ', ' hadz ', ' com' ] console.log(str.split('-'))

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

index.js
const str = 'bobby - hadz - com'; const arr = str.split('-') .map(element => element.trim()); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

On each iteration, we use the String.trim() method to remove the leading and trailing spaces from the string.

index.js
// ๐Ÿ‘‡๏ธ "abc" console.dir(' abc '.trim());

The map() method returns a new array containing the values returned from the callback function.

# Dealing with multiple consecutive separators

There is an edge case that you might need to handle - there might be 2 of the same separators next to one another.

In the case that there are multiple separator characters next to one another, we'd get a bunch of empty strings.

index.js
// ๐Ÿ‘‡๏ธ ['one', '', ' two ', '', ' three'] console.log('one -- two -- three'.split('-'));

We're splitting on each hyphen, but have two hyphens next to one another, so we get an empty string for the second hyphen.

To handle this scenario, we can use the Array.filter() method to remove the empty strings from the array.

index.js
const str = ' one -- two -- three '; const arr = str .split('-') .map(element => element.trim()) .filter(element => element !== ''); console.log(arr); // ๐Ÿ‘‰๏ธ ['one', 'two', 'three']

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

On each iteration, we check if the element is not equal to an empty string and return the result.

The filter() method returns a new array that only contains the elements that meet the condition.

# Split String and remove surrounding Spaces using replaceAll()

An alternative approach would be to remove all spaces from the string before calling split().

index.js
const str = 'bobby - hadz - com'; const arr = str.replaceAll(' ', '').split('-') console.log(arr) // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Strings are immutable in JavaScript.

The last step is to split the string that doesn't contain any spaces on the separator.

# Split String and remove surrounding Spaces using regex

An alternative approach is to call the String.split() method with a regular expression.

index.js
const str = 'bobby - hadz - com'; const arr = str.trim().split(/\s*-\s*/); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

We passed a regular expression in the call to the split() method.

The forward slashes / / mark the beginning and end of the regex.

The \s special character matches spaces, tabs and newlines.

The asterisk * matches the preceding item (whitespace) zero or more times.

We then have a hyphen - and zero or more whitespace characters.

Make sure to replace the hyphen with the character you need to split by, e.g. a comma.

index.js
const str = 'bobby , hadz , com'; const arr = str.trim().split(/\s*,\s*/); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

The asterisk * matches zero or more consecutive whitespace characters, so the elements in the array won't have any surrounding spaces.

The format for the regular expression is /\s*{char}\s*/.

# Split a String by Space or Comma using JavaScript

You can use the split() method to split a string by space or comma.

index.js
const str = 'bobby hadz, com'; const result = str.split(/[, ]+/); console.log(result); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

We passed a regular expression to the split() method.

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. 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 = 'bobby hadz,,,, com'; const result = str.split(/[, ]+/); console.log(result); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

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

# Split a string by whitespace or comma

If you need to split a string by a whitespace character or a comma, update the regular expression.

index.js
const str = 'bobby \t\n hadz,,,,\n com'; const result = str.split(/[,\s]+/); console.log(result); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

The \s special character matches spaces, tabs and new lines.

# Handling edge cases

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 = 'bobby hadz, com,'; const result = str.split(/[, ]+/); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com', '' ] 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 remove the empty strings from the array.

index.js
const str = 'bobby hadz, com,'; const result = str.split(/[, ]+/).filter(element => element); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] 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.

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

All other values are truthy.

Empty strings are falsy values, so they get excluded from the result.

Alternatively, you could shorten this further, by passing the Boolean() constructor to the filter() method.

index.js
const str = 'bobby hadz, com,'; const result = str.split(/[, ]+/).filter(Boolean); // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(result);

The Boolean() constructor 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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev