In this article, we’ll learn how to easily include spaces between the characters of a string in JavaScript.
1. The String split() and Split join() Methods
To add a space between characters of a string, call the split()
method on the string to get a character array, then call the join()
method on the array to join the characters with a space separator.
For example:
function addSpace(str) {
return str.split('').join(' ');
}
const str1 = 'coffee';
const str2 = 'banana';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
The String
split()
method splits a string in an array of substrings, using the specified separator.
const str1 = 'coffee,milk,tea';
const str2 = 'sun-moon-star';
console.log(str1.split(',')); // [ 'coffee', 'milk', 'tea' ]
console.log(str2.split('-')); // [ 'sun', 'moon', 'star' ]
By using an empty string (''
) as the separator, we split up all the string characters into separate array elements.
const str1 = 'coffee';
const str2 = 'banana';
// Passing an empty string ('') to the split method
// [ 'c', 'o', 'f', 'f', 'e', 'e' ]
console.log(str1.split(''));
// [ 'b', 'a', 'n', 'a', 'n', 'a' ]
console.log(str2.split(''));
The String
join()
method combines each string in an array with a separator. It returns a new string containing the concatenated array elements.
const arr = ['a', 'b', 'c', 'd'];
console.log(arr.join(' ')); // a b c d
console.log(arr.join('-')); // a-b-c-d
console.log(arr.join('/')); // a/b/c/d
So passing a space character to join()
separates the characters by a space in the resulting concatenation.
There will be instances where the string already contains spaces between some characters. In such cases, our approach would add even more spaces between the characters.
function addSpace(str) {
return str.split('').join(' ');
}
// These strings have spaces between some characters
const str1 = 'co ffee';
const str2 = 'bana na';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
This is because a space (' '
) is a character too, like a letter, and calling split()
would make it a separate element in the array that will be combined with additional spaces.
// These strings have spaces between some characters
const str1 = 'co ffee';
const str2 = 'bana na';
// The space characters are separate elements of the
// array from split()
/**
* [
'c', 'o', ' ',
' ', 'f', 'f',
'e', 'e'
]
*/
console.log(str1.split(''));
/**
* [
'b', 'a', 'n',
'a', ' ', ' ',
'n', 'a'
]
*/
console.log(str2.split(''));
If we want to avoid the multiple spacing of the characters, we can insert a call to the filter()
method between split()
and join()
.
function addSpace(str) {
return str
.split('')
.filter((item) => item.trim())
.join(' ');
}
// The strings have spaces between some characters
const str1 = 'co ffee';
const str2 = 'bana na';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
The Array
filter()
method returns a new array containing only the elements from the original array for which a truthy value is returned from the testing callback function passed to filter()
. Calling trim()
on a space (' '
) results in an empty string (''
), which is not a truthy value in JavaScript. So the spaces are excluded from the resulting array returned from filter()
.
Tip
In JavaScript, there are only six falsy values: false
, null
, undefined
, 0
, ' '
(the empty string), and NaN
. Every other value is truthy.
2. for…of Loop
For a more imperative approach, we can use the JavaScript for...of
loop to add a space between the characters of a string.
function addSpace(str) {
// Create a variable to store the eventual result
let result = '';
for (const char of str) {
// On each iteration, add the character and a space
// to the variable
result += char + ' ';
}
// Remove the space from the last character
return result.trimEnd();
}
const str1 = 'coffee';
const str2 = 'banana';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
To handle the scenario discussed earlier, where the string has spaces between some characters, call trim()
on the character of each iteration, and add an if
check to ensure that it is truthy, before adding it and the space to the accumulating result:
function addSpace(str) {
// Create a variable to store the eventual result
let result = '';
for (const char of str) {
// On each iteration, add the character and a space
// to the variable
// If the character is a space, trim it to an empty
// string, then only add it if it is truthy
if (char.trim()) {
result += char + ' ';
}
}
// Remove the space from the last character
return result.trimEnd();
}
const str1 = 'co ffee';
const str2 = 'bana na';
console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.