Last updated: Mar 4, 2024
Reading timeยท9 min
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.
const str = 'bobby hadz com'; const arr = str.split(' '); // ๐๏ธ [ 'bobby', 'hadz', 'com' ] console.log(arr);
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:
Name | Description |
---|---|
separator | The pattern describing where each split should occur. |
limit | An 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.
// ๐๏ธ [ 'bobby', 'hadz' ] console.log('bobby hadz'.split(' ')); // ๐๏ธ [ 'bobby', 'hadz' ] console.log('bobby-hadz'.split('-'));
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.
const str = ' bobby hadz com '; const arr = str.trim().split(/\s+/); console.log(arr); // ๐๏ธ [ 'bobby', 'hadz', 'com' ]
The String.trim() method removes the leading and trailing whitespace from a string and returns a new string, without modifying the original string.
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.
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).
+
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.
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.
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 cheat sheet by MDN.
It contains a table with the name and the meaning of each special character with examples.
You can use the split()
method with a regex to split a string, keeping the
whitespace.
const str = 'bobby hadz com'; const arr = str.split(/(\s+)/); // ๐๏ธ [ 'bobby', ' ', 'hadz', ' ', 'com' ] console.log(arr);
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:
Name | Description |
---|---|
separator | The pattern describing where each split should occur. |
limit | An 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.
()
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.
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.
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()
and join()
This is a three-step process:
split()
method to split the string on each space.join()
method to join the array into a string.split()
method to split the string and keep the whitespace.const str = 'bobby hadz com'; const result = str.split(' ').join('# #').split('#'); console.log(result); // ๐๏ธ [ 'bobby', ' ', 'hadz', ' ', 'com' ]
We first split the string on each space to get an array containing the words in the string.
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.
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.
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.
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.
To split a string and trim the surrounding spaces:
split()
method to split the string into an array.map()
method to iterate over the array.trim()
method on the string to remove the surrounding spaces.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:
Name | Description |
---|---|
separator | The pattern describing where each split should occur. |
limit | An 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.
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.
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.
// ๐๏ธ "abc" console.dir(' abc '.trim());
The map()
method returns a new array containing the values returned from the
callback function.
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.
// ๐๏ธ ['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.
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.
replaceAll()
An alternative approach would be to remove all spaces from the string before
calling split()
.
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:
Name | Description |
---|---|
pattern | The pattern to look for in the string. Can be a string or a regular expression. |
replacement | A 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.
An alternative approach is to call the String.split()
method with a regular
expression.
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.
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*/
.
You can use the split()
method to split a string by space or comma.
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.
+
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.
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.
If you need to split a string by a whitespace character or a comma, update the regular expression.
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.
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.
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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: