Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting text with tabs or spaces

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?

like image 587
Artem P Avatar asked Jun 20 '13 21:06

Artem P


People also ask

Should you use spaces or tabs?

Tabs Debate. Pro-spaces programmers argue that using the space bar makes the layout more flexible. However, pro-tabs users rebut saying tabs makes code more readable and aesthetically pleasing.

Should I use tabs in code?

The analysis performed by the team at Stack Overflow found that programmers who use spaces instead of tabs are making more money. David Robinson, the data scientist who performed this study found that programmers using space over tabs made an average of 9 percent more each year than their tab using counterparts.

How do you put a tab in a string?

If you use the "\t" escape character once, it adds one tab space in string. This tab character can be used in a string or just directly passed and concatenated with a string and written to console.

What does \t do in HTML?

It is equivalent to the tab character as such. Thus, from the HTML viewpoint, there is no need to “escape” it using the character reference; but you may do so e.g. if your editing program does not let you enter the character conveniently.


1 Answers

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     
like image 162
maximus Avatar answered Nov 11 '22 09:11

maximus