views:

184

answers:

2

Background: I've written this before but I don't like the approach. The reason is because Javascript does not have "sprintf" and that is something I use heavily if the language supports it.

Question: How would you use javascript to go from BEFORE to AFTER? If anyone has a solution with very small number of lines of code, or something from a javascript string library, that would be informative. TIA.

BEFORE:

red| lightblue| green 
cherry| ice| mint 
round| cubic| flowery

AFTER:

red    | lightblue | green 
cherry | ice       | mint 
round  | cubic     | flowery

Disclaimer: This is not homework or any such thing, just looking for new ideas. Also, this is not browser-based javascript. This is not a web-development question, but a javascript programming question.

+1  A: 
function pad(str, len) {
    for (var count = len - str.length; count > 0; count--) {
        str = str + " ";
    }
    return str;
}

console.log(pad("red", 7) + "| " + pad("lightblue", 9) + "| " + pad("green", 7));
//etc.

Yeah, concatenating characters one by one is inefficient, but generally you'll only have a small number of iterations.

Anthony Mills
Yeah, that's exactly what i was trying to avoid. Just wondering if there is an alternate approach i haven't thought of ... regex tricks or something ...
dreftymac
Well, I suppose there are other fun ways of doing it. Like if you know the maximum length, you could do something like `return str + " ".substr(str.length)` (to always pad it to 9) but other than that... I got nothin'. :)
Anthony Mills
Argh, stupid HTML. Assume the `" "` above has nine spaces in it.
Anthony Mills
+2  A: 

If you like sprintf, why not look for a JavaScript implementation for it?

Ron Klein
Hmm .. good point
dreftymac
Careful, the first hit there's implementation doesn't support padding values.
Anthony Mills