How to add white space to left of a string with JavaScript?

Sometimes, we want to add white space to left of a string with JavaScript.

In this article, we’ll look at how to add white space to left of a string with JavaScript.

How to add white space to left of a string with JavaScript?

To add white space to left of a string with JavaScript, we can use the string padStart method.

For instance, we write:

const str = 'blah'
const paddedStr = str.padStart(10, ' ')
console.log(paddedStr)

to call str.padStart with 10 and ' ' to pad the string to length 10 by prepending spaces to the string.

Therefore, paddedStr is ' blah'.

Conclusion

To add white space to left of a string with JavaScript, we can use the string padStart method.