Formatting text with tabs or spaces
Asked Answered
D

3

11

I have object like this:

{
 Name: "John"
 Location: "Unknown"
 Type: "Unknown"
 Status: "Unknown"
 Phone_number: "Unknown"
}

Need to format it like this (with tabs or spaces):

Name:           John // three tabs
Location:       Unknown // two tabs
Type:           Unknown // three tabs
Status:         Unknown // three tabs
Phone_number:   Unknown // one tab

Java and Perl has this functionality in printf, but how to do this in javascript?

Drenthe answered 20/6, 2013 at 21:29 Comment(0)
D
14

Ok. Found here:

/**
 * object.padding(number, string)
 * Transform the string object to string of the actual width filling by the padding character (by default ' ')
 * Negative value of width means left padding, and positive value means right one
 *
 * @param       number  Width of string
 * @param       string  Padding chacracter (by default, ' ')
 * @return      string
 * @access      public
 */
String.prototype.padding = function(n, c)
{
        var val = this.valueOf();
        if ( Math.abs(n) <= val.length ) {
                return val;
        }
        var m = Math.max((Math.abs(n) - this.length) || 0, 0);
        var pad = Array(m + 1).join(String(c || ' ').charAt(0));
//      var pad = String(c || ' ').charAt(0).repeat(Math.abs(n) - this.length);
        return (n < 0) ? pad + val : val + pad;
//      return (n < 0) ? val + pad : pad + val;
};

This not works with tabs, but works with spaces exactly how I describe in question.

For my example code will be:

$.each(myObj, function(myKey, myVal) {

   myOut += myKey.padding(20) + " = " + myVal + "\r\n";

});

Output will be:

Name                 = John
Location             = Unknown
Type                 = Unknown
Status               = Unknown
Phone_number         = Unknown
Drenthe answered 22/6, 2013 at 15:8 Comment(1)
This is very helpful, however it doesn't work with multiple padding in one line.Bevon
A
10

The String.prototype.padEnd(targetLength, padString) method will do the job, it is documented here. The padString parameter is set to a single-space string if omitted.

Example:

console.log(`   ${'Player'.padEnd(19)} ` +
    `${'MATCH'.padEnd(8) } ` +
    `${'SCORE'.padEnd(8) } `
);
for (const player of this.players) {
    console.log(` - ${player.name.padEnd(20)} ` +
        `${player.matches.length.toString().padEnd(8) } ` +
        `${player.score.toString().padEnd(8) } `
    );
}

Result:

   Player              MATCH    SCORE   
 - Bradly               5        15      
 - Sam                  4        9       
 - Dew                  3        5     
Archfiend answered 24/9, 2021 at 7:49 Comment(2)
Cleaner example jsbin.comDrenthe
Working with myString.padEnd(x) in combination with a monospace font is imho the best solution and should be the accepted answer.Prejudicial
D
7

EDIT You can add more tabs by using '\t'. Each '\t' means one tab, so in the console.log you can use more console.log(prop + ":\t\t\t" + obj[prop]);

Pass your object to this function (this works for any object):

function printObject(obj)
  for(var prop in obj){
   if (obj.hasOwnProperty(prop)) {
    console.log(prop + ":\t" + obj[prop]);
   }
 }

You can also get a pretty similar output (but with quotes) by using

JSON.stringify(obj, null, 2); 

This will basically print your objects in jason format and will use the last argument (the 2) as the number of separator spaces.

Decoder answered 20/6, 2013 at 21:37 Comment(3)
First function adds only one tab, if key will have long word or few words one tab will be not enough. Even in my sample first line requires two tabs.Drenthe
@ancap Did you try to add more tabs, like :\t\t, or even :\t\t\t?Callender
I edited first post. As you can see in first line - three tabs, in second - two, in third and fourth - three, in fifth - one.Drenthe

© 2022 - 2024 — McMap. All rights reserved.