Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *