Javascript: quick script to line up pipe-delimited text (or any-character-delimited text)
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 ide开发者_高级运维as. Also, this is not browser-based javascript. This is not a web-development question, but a javascript programming question.
If you like sprintf
, why not look for a JavaScript implementation for it?
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.
精彩评论