To add spacing or padding to the beginning of a string, you can use the padStart()
string method in JavaScript.
Consider this string,
// a string
const str = "Hello";
Let's add 5 spaces to the beginning of the string using the padStart()
string method like this,
// a string
const str = "Hello";
// add 5 spaces to the beginning
// of string using padStart() method
const paddedStr = str.padStart(10);
console.log(paddedStr); // " Hello"
Now you might think why did we use 10
instead of 5
. Because the padStart()
method starts counting characters from the start of the string. Since we already had 5
letters and passing 5
won't do the trick.
// a string
const str = "Hello";
// ❌ passing 5 won't make 5 spaces we have
// to accomodate for the whole string
const paddedStr = str.padStart(5);
// 😕 Not what we expected
console.log(paddedStr); // "Hello"
But if you don't want to hardcode like this, there's another way to automatically pad 5
spaces to the beginning of the string.
It can be done using the length
property of the string. First, get the length of the string then add 5 spaces like this,
// a string
const str = "Hello";
// add 5 spaces to the beginning
// of string using padStart() method
const paddedStr = str.padStart(str.length + 5);
console.log(paddedStr); // " Hello"
Nifty Trick 🔥. Right?
You can also choose to have any string instead of spaces by passing the string as the second argument to the padStart()
method like this.
// a string
const str = "Hello";
// add 5 spaces to the beginning
// of string using padStart() method
const paddedStr = str.padStart(str.length + 5, "*");
console.log(paddedStr); // "*****Hello"
See this example live in JSBin.
Key things to take away using the padStart()
string method:
- It requires the absolute number of spaces or padding to be added to the beginning of the string as the first argument.
- You can have an optional string to be used instead of spaces if provided as the second argument to the
padStart()
string method. - the method returns a new string