Brian T Hannan
Brian T Hannan

Reputation: 4015

How is this Javascript doing padding to the right?

I have this Javascript and I'm trying to figure out exactly what it's doing:

str = str + Array(len + 1 - str.length).join(padch);

*Note: I know that str is the string we are working with, len is the length of that string we are working with, padch is the character we want to pad with. I'm not sure what Array and join are doing here.

Upvotes: 1

Views: 45

Answers (1)

Halcyon
Halcyon

Reputation: 57703

This is the interesting part:

Array(len + 1 - str.length).join(padch);

It uses this syntax:

Array(10); // creates an array with 10 undefined values

Then you join it together, with the padcharacter.

Array(10).join(","); // gives 9 comma's (9 because 10-1)

Then len + 1 - str.length is the math to generate the correct amount of padding characters.

Upvotes: 4

Related Questions