How to use padStart & padEnd — ES7
I thought it would be cool if i spent some time researching and learning some ES7 features and share that with you!
Happy new year by the way ☺
You can use an online code editor such as https://jsfiddle.net/ to write these statements in and then open the “web inspector” to see the output in the console.
In incredibly simple terms “padStart" is used to “pad" or “concatenate" a string to the start of another string up to a specified length. So let’s say we have a variable like the below.
let myVar = “6";
We also have another variable below called “myPaddedStartString" which is used to invoke the “padStart" method of the String object to pad the letter “C" to the left of the “myVar" variable until the length of the “myPaddedStartString" method is 10 characters.
let myPaddedStartString = myVar.padStart(10,”C”);
So the output of this would be
So we have 9 letter “C"s to the left or start of the number 6.
You can also pad multiple characters to the start of the initial string, however, if you have multiple characters to pad and the string meets the length given within “padStart" then the remaining characters will be cut off/truncated. Also, the default value for the padstring is a space character but in our example above it is “C". An example of “padStart" is below.
let myVarTwo = “5";let mySecondPadStartString = myVarTwo.padEnd(20,”ABCD");
So the output below would be
As you can see the string is 20 characters however the last “ABCD" has been cut off at “ABC" because the “padStart" length was limited to 20 characters within the “mySecondPadStartString” variable.
PadEnd works the exact same way as “padStart" ,however, the characters are added to the end of the string. An example is below.
let myPadEndVar= "6";let myFinalPadEndString= myPadEndVar.padEnd(20,"ABCD");console.log(myFinalPadEndString);6ABCDABCDABCDABCDABC
Just to end, the browsers that support this are
Internet explorer- Nope (what a surprise lol)
Apologies for the short article but I wanted to write a nice short article to get back into the swing of things so I can prepare myself to write longer and more thought out pieces in the future
Dont forget to clap, share and express what you like/didnt like about the article
Happy new year and stay safe!