Last updated: Mar 4, 2024
Reading timeยท6 min
for...of
To add a space between the characters of a string:
String.split()
method to split the string into an array of
characters.Array.join()
method to join the characters with a space separator.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
The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.
// ๐๏ธ [ '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:
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. |
When called with an empty string separator, the split()
method converts the
string into an array of characters.
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.
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.
You might have to handle the scenario where your string already contains spaces.
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'
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).
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.
We can remove the empty strings by using the Array.filter
method.
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
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.
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.
Alternatively, you can use the String.repeat()
method.
The space is repeated the specified number of times and is added to the string.
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"
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.
console.dir('a'.repeat(3)); // ๐๏ธ "aaa" console.dir(' '.repeat(3)); // ๐๏ธ " "
The first and second examples show how to append and prepend the spaces to the string.
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.
This is a three-step process:
slice()
method to get the parts before and after the index.repeat()
method to create a string containing N spaces.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 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:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The 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.
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.
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.
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 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.
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.
const str = 'baz'; const padEnd = str.padEnd(6, ' '); console.log(padEnd); // ๐๏ธ "baz " const padStart = str.padStart(6, ' '); console.log(padStart); // ๐๏ธ " baz"
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:
Name | Description |
---|---|
targetLength | The string gets padded with the pad string up to this length. |
padStart | The 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.
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.
for...of
This is a three-step process:
for...of
loop to iterate over the string.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 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.
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 last step is to call the String.trimEnd()
method to remove the trailing
space from the string.
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.