K3NN3TH K3NN3TH - 29 days ago 16
Javascript Question

javascript - adding white space to left of string

Is there a better way to add x amount of white space to a string?

str = "blah";
x = 4;

for (var i = 0; i < x; i++){
str = ' ' + str;
}

return str;

Answer

Could do it like this, prevents the loop.

str = str + new Array(x + 1).join(' ')

Comments