Add a Space between the Characters of a String in JS

avatar
Borislav Hadzhiev

Last updated: Mar 4, 2024
6 min

banner

# Table of Contents

  1. Add a Space between the Characters of a String in JavaScript
  2. Add a specific Number of Spaces to a String in JavaScript
  3. Add a specific number of spaces to the middle of a string
  4. Add a Space between the Characters of a String using for...of

# Add a Space between the Characters of a String in JavaScript

To add a space between the characters of a string:

  1. Use the String.split() method to split the string into an array of characters.
  2. Use the Array.join() method to join the characters with a space separator.
index.js
function addSpace(str) { return str.split('').join(' '); } const result1 = addSpace('apple'); console.log(result1); // ๐Ÿ‘‰๏ธ a p p l e const result2 = addSpace('pear'); console.log(result2); // ๐Ÿ‘‰๏ธ p e a r

add space between characters of string

The code for this article is available on GitHub

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

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

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.

When called with an empty string separator, the split() method converts the string into an array of characters.

index.js
const str = 'apple'; // ๐Ÿ‘‡๏ธ ['a', 'p', 'p', 'l', 'e'] console.log(str.split(''));

The Array.join() method concatenates all of the elements in an array using a separator.

index.js
const arr = ['a', 'b', 'c']; console.log(arr.join(' ')); // ๐Ÿ‘‰๏ธ a b c console.log(arr.join('-')); // ๐Ÿ‘‰๏ธ a-b-c console.log(arr.join(',')); // ๐Ÿ‘‰๏ธ a,b,c

The only argument the Array.join() method takes is a separator - the string used to separate the elements of the array.

# Dealing with strings that already contain spaces

You might have to handle the scenario where your string already contains spaces.

index.js
function addSpace(str) { return str.split('').join(' '); } const str1 = 'app le'; const str2 = 'pe ar'; console.dir(addSpace(str1)); // ๐Ÿ‘‰๏ธ 'a p p l e' console.dir(addSpace(str2)); // ๐Ÿ‘‰๏ธ 'p e a r'

dealing with strings that already contain spaces

The code for this article is available on GitHub

We added spaces between the characters of a string that already contains spaces.

This is because the split() method splits the string on each character (including each space).

index.js
const str = 'app le'; // ๐Ÿ‘‡๏ธ ['a', 'p', 'p', ' ', ' ', 'l', 'e'] console.log(str.split(''));

We split the string on each character, so the array contains empty string elements.

# Removing empty string elements from the array

We can remove the empty strings by using the Array.filter method.

index.js
function addSpace(str) { return str .split('') .filter(element => element.trim()) .join(' '); } const str1 = 'app le'; const str2 = 'pe ar'; console.log(addSpace(str1)); // ๐Ÿ‘‰๏ธ a p p l e console.log(addSpace(str2)); // ๐Ÿ‘‰๏ธ p e a r

removing empty string elements from array

The code for this article is available on GitHub

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

On each iteration, we use the trim() method to remove any leading or trailing spaces from the array element.

When we trim a string that contains only spaces, we get an empty string.

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

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

Empty strings are falsy values, so they don't get added to the new array.

# Add a specific Number of Spaces to a String in JavaScript

Alternatively, you can use the String.repeat() method.

The space is repeated the specified number of times and is added to the string.

index.js
const str = 'baz'; // โœ… add spaces to end const padEnd = str + ' '.repeat(3); console.dir(padEnd); // ๐Ÿ‘‰๏ธ "baz " // โœ… add spaces to start const padStart = ' '.repeat(3) + str; console.dir(padStart); // ๐Ÿ‘‰๏ธ " baz"

add specific number of spaces to string

The code for this article is available on GitHub

The only parameter the String.repeat() method takes is the number of times the string should be repeated.

Here is an example that repeats a space 3 times.

index.js
console.dir('a'.repeat(3)); // ๐Ÿ‘‰๏ธ "aaa" console.dir(' '.repeat(3)); // ๐Ÿ‘‰๏ธ " "
We can use the addition (+) operator to concatenate the strings.

The first and second examples show how to append and prepend the spaces to the string.

index.js
const str = 'baz'; // โœ… add spaces to end const padEnd = str + ' '.repeat(3); console.log(padEnd); // ๐Ÿ‘‰๏ธ "baz " // โœ… add spaces to start const padStart = ' '.repeat(3) + str; console.log(padStart); // ๐Ÿ‘‰๏ธ " baz"

If you need to add spaces to the middle of the string, use the String.slice() method.

# Add a specific number of spaces to the middle of a string

This is a three-step process:

  1. Use the slice() method to get the parts before and after the index.
  2. Use the repeat() method to create a string containing N spaces.
  3. Use the addition (+) operator to concatenate the strings.
index.js
const str = 'baz'; const index = str.indexOf('a'); const padMiddle = str.slice(0, index) + ' '.repeat(3) + str.slice(index); console.dir(padMiddle); // ๐Ÿ‘‰๏ธ 'b az'
The code for this article is available on GitHub

The String.slice() method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe index of the first character to exclude from the returned substring

In the first call to the slice method, we get the substring from index 0, up to but not including the index of the first occurrence of the a character in the string.

index.js
const str = 'baz'; const index = str.indexOf('a'); console.log(str.slice(0, index)); // ๐Ÿ‘‰๏ธ 'b'

We added 3 spaces to the result and chained another call to the slice() method.

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

index.js
const str = 'baz'; const index = str.indexOf('a'); console.log(str.slice(index)); // ๐Ÿ‘‰๏ธ 'az'

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

index.js
function addSpacesAtIndex(str, index, numSpaces) { return ( str.slice(0, index) + ' '.repeat(numSpaces) + str.slice(index) ); } const str = 'baz'; console.dir(addSpacesAtIndex(str, 1, 2)); // ๐Ÿ‘‰๏ธ 'b az' console.dir(addSpacesAtIndex(str, 1, 3)); // ๐Ÿ‘‰๏ธ 'b az' console.dir(addSpacesAtIndex(str, 1, 4)); // ๐Ÿ‘‰๏ธ 'b az'
The code for this article is available on GitHub

The function takes a string, an index and a number of spaces and adds the specified number of spaces to the string at the given index.

An alternative approach is to use the String.padEnd and String.padStart methods.

# Add a specific Number of Spaces to a String using padEnd and padStart

The padEnd and `padStart methods take the maximum length of the new string and the fill string and return the padded string.

index.js
const str = 'baz'; const padEnd = str.padEnd(6, ' '); console.log(padEnd); // ๐Ÿ‘‰๏ธ "baz " const padStart = str.padStart(6, ' '); console.log(padStart); // ๐Ÿ‘‰๏ธ " baz"
The code for this article is available on GitHub

Using the padEnd and padStart methods is a little tricky because the first parameter is the maximum length the new string should have.

The String.padStart() method pads the current string with the provided string until the resulting string reaches the given length.

The padStart method takes the following 2 arguments:

NameDescription
targetLengthThe string gets padded with the pad string up to this length.
padStartThe string to pad the current string with.

The padEnd method takes the same parameters but pads the string at the end.

Using the padEnd and padStart methods is a little tricky because the first parameter is the maximum length the new string should have.

If you have a string that contains 3 characters and specify a maximum length of 6, it would only get padded with 3 extra characters.

You can use the string's length to determine how many spaces should be added.

index.js
const str = 'baz'; const padEnd = str.padEnd(str.length + 3, ' '); console.dir(padEnd); // ๐Ÿ‘‰๏ธ 'baz ' const padStart = str.padStart(str.length + 3, ' '); console.dir(padStart); // ๐Ÿ‘‰๏ธ ' baz'

The code sample adds 3 spaces to the beginning and end of the string.

# Add a Space between the Characters of a String using for...of

This is a three-step process:

  1. Declare an empty string variable.
  2. Use a for...of loop to iterate over the string.
  3. On each iteration, add the character and a space to the string.
index.js
function addSpace(str) { let spaced = ''; for (const char of str) { if (char.trim()) { spaced += char + ' '; } } return spaced.trimEnd(); } const str1 = 'app le'; const str2 = 'pe ar'; console.dir(addSpace(str1)); // ๐Ÿ‘‰๏ธ a p p l e console.dir(addSpace(str2)); // ๐Ÿ‘‰๏ธ p e a r
The code for this article is available on GitHub

The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.

We need to handle the scenario where the string already contains spaces, so we used the trim() method.

We check if each character is not a space before adding the character and a space to the new string.

If you don't need to handle a scenario where your string contains spaces, remove the if block.

index.js
function addSpace(str) { let spaced = ''; for (const char of str) { spaced += char + ' '; } return spaced.trimEnd(); } const str1 = 'apple'; const str2 = 'pear'; console.dir(addSpace(str1)); // ๐Ÿ‘‰๏ธ a p p l e console.dir(addSpace(str2)); // ๐Ÿ‘‰๏ธ p e a r
The code for this article is available on GitHub

The last step is to call the String.trimEnd() method to remove the trailing space from the string.

index.js
console.dir('a p p l e '.trimEnd()); // ๐Ÿ‘‰๏ธ 'a p p l e'

There is a trailing space at the end of the string because we add a space after each character in our for...of loop.

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