Home » Javascript » Indention/align each String row in JavaScript when exporting as a .txt file

Indention/align each String row in JavaScript when exporting as a .txt file

Posted by: admin August 19, 2018 Leave a comment

Questions:

I am using Angular, TypeScript/JavaScript to test this.

I have formatted each row with a new line at the back of the code

formattedStr += car.Name + ' | ' + car.Color + ' | ' + car.Brand + '\r\n'

Then exported it with

const file = new Blob([formattedStr], { type: 'text/plain' });
saveAs(file, 'myfilename');

Looks like this in .txt file

Name ABC | Color A | Brand XYZ
Name ABCDEF | Color SDA | Brand ZXXYZ
Name ABCEA | Color ADS | Brand CVDRXYZ

Now, attempts to format each row to align, expecting something like

Name ABC    | Color A   | Brand XYZ
Name ABCDEF | Color SDA | Brand ZXXYZ
Name ABCEA  | Color ADS | Brand CVDRXYZ

Had some trouble in creating Dynamic Indentions based on the longest word in each column. Any suggestions?

I have tested with \t to create symbol for tab but it creates a fixed indent in every row which makes every row not aligned.

Name ABC  | Color A  | Brand XYZ
Name ABCDEF | Color SDA  | Brand ZXXYZ
Name ABCEA | Color ADS  | Brand CVDRXYZ
Answers: