Add specific Number of Spaces to a String in JavaScript


Borislav Hadzhiev

Fri Nov 19 20212 min read

Add specific Number of Spaces to a String #

Use the repeat() method to add a number of spaces to a string, e.g. str + ' '.repeat(3). The repeat() method allows us to repeat the string on which it was called a number of times and returns the result. You can then add the number of spaces at any position in 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" // ✅ add spaces to middle const index = str.indexOf('a'); const padMiddle = str.slice(0, index) + ' '.repeat(3) + str.slice(index); console.log(padMiddle); // 👉️ "b az"

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

In the examples, we repeat a space 3 times.

console.log('a'.repeat(3)); // 👉️ "aaa" console.log(' '.repeat(3)); // 👉️ " "

We can use the addition (+) operator to add the spaces at any position in the string.

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

The third example uses the String.slice method to insert the spaces at a specific index.

The two parameters we passed to the slice() method are:

  1. start index - the index of the first character to be included in the new string
  2. end index - go up to, but not including this index

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

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

The only parameter we passed to the second call is the start index. If you only provide 1 parameter to the slice method, it goes to the end of the string.

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

Use the padEnd() and padStart() method to add spaces to the end or beginning of a string, e.g. str.padEnd(6, ' ');. The methods take 2 parameters - the maximum length of the new string and the fill string and returns 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.

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

Which approach you pick is a matter of personal preference. I'd go with the repeat() method as I find it more intuitive and readable.
Use the search field on my Home Page to filter through my more than 1,000 articles.