1

I use javascript to get a string (name) that I will eventually paste to a text file with other data (a grade).

var name = "Joe Smith";
var n = str.length;
document.getElementById("sum").value="" + name + " " + grade

I want to create a column effect that will make the text file easier to read by reading the length of the name string then adding a number of spaces relative to the length of the str variable.

So, if the string length is 15 spaces, I will add 5 spaces to make it 20. And if the string length is 10, I will add 10 spaces to make it 20 too. When I use the PRE tag, all the grade variables should line up.

Should I use the join() function somehow? I'm not sure how. Any suggestions?

user3283304
  • 149
  • 1
  • 2
  • 14
  • Thank you for your attention. With respect, I believe I am attempting to do something much more simple. I want to add spaces to the right side of variable name. I can't seem to extract an answer that will help me from that questions. – user3283304 Apr 24 '15 at 12:55

2 Answers2

1
document.getElementById("sum").value = name + Array(20 - name.length).join(" ") + grade
Peter
  • 16,453
  • 8
  • 51
  • 77
1

As a function:

var name = "Joe Smith";

// give it a string and a number of total spaces
function pad(str, n) {
    return str + Array(n - str.length).join(" ");
}

document.write(pad(name, 20));
VF_
  • 2,627
  • 17
  • 17