Formatting Strings in JavaScript when saving as a .txt file with proper indentation

Utilizing Angular and TypeScript/JavaScript for testing purposes.

Each row has been formatted with a newline at the end of the code.

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

The data is then exported using:

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

When viewed in a .txt file, it appears like this:

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

Efforts are being made to align each row properly as follows:

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

Encountering challenges in creating dynamic indentations based on the length of the longest word in each column. Any advice?

Experimented with \t for tab spacing but encountered issues with fixed indentation in every row, causing misalignment.

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

Answer №1

If you have the ability to bundle, install or replicate the script, you can make use of the text-table npm package.

var table = require('text-table');
var t = table([
    [ 'Product X', 'Color A', 'Brand Y' ],
    [ 'Product XYX', 'Color Z', 'Brand QWERTY' ],
    [ 'Product XYZ', 'Color LMN', 'Brand ABCD' ]
], { hsep :' | '});

console.log(t);

Result:

Product X   | Color A  | Brand Y
Product XYX | Color Z | Brand QWERTY
Product XYZ | Color LMN | Brand ABCD

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

md-sidenav causing anchor tags to malfunction

Having issues with Angular 4, Angular Material 2, and Node 8 (although the problem was present in version 6 as well). My md-sidenav with anchor tags as content is not responding to CSS styling or clicks. I've checked for open tags, tried different mod ...

Ways to update vuex state using mutations

Currently, I am facing an issue while working on an app where I'm attempting to change the Vuex state using mutations but it's not functioning as expected. Initially, the state.status is set as an empty string, and my goal is to update it to the ...

How can I retrieve the name of the upcoming middleware function in Express.JS?

Hey there, I'm currently facing a challenge with retrieving the names of middleware functions in a specific request route. Let's consider the code snippet below as an example: const authorizeRoute = (req,res,next) => { let nextFunctionName = ...

Encountering an error when updating Angular 2 dynamic forms: "Expression has been altered"

I'm struggling with creating a dynamic nested form that's quite complex, but I just can't seem to get it functioning properly. Essentially, the end result should look similar to this: Desired outcome mockup The user will need to choose a f ...

Public directory assets not accessible

After working extensively with Node and Angular, I realized my back-end structure needed some serious attention. In an effort to streamline my process, I decided to separate the client and server components and create a reusable skeleton for future applica ...

Successfully Determining User Identity with Ajax Authentication

Currently, I am facing a security issue with my login page that uses an Ajax request for user authentication. The password entered by the user is sent as plain text in the form data of the Ajax request, making it vulnerable to interception by sniffing tool ...

How come submitting a form without refreshing does not update the database with new values?

I'm encountering an issue with my form and script that is supposed to connect to the operation.php class. Despite having everything set up correctly, the data is not being added to the database and the page does not refresh. I'm perplexed as to ...

Where can I find the previous version of three.js? What is causing the incompatibility between the old and new versions of

Why is my app facing issues with the updated version of three.js? Can I find the previous version of three.js and why isn't the new version compatible? ...

Unable to properly structure data in JSON request

Trying to fill JSON request with data from phpsearch.php file (displayed below) <?php include "base.php"; $name = $_GET["name"]; $query = "SELECT lat, lng FROM markers WHERE name = '".$name."'"; $result = mysql_query($query); $json = array(); ...

Tips for choosing one specific element among multiple elements in cheerio nodejs

Currently, I'm attempting to extract links from a webpage. However, the issue I'm encountering is that I need to extract href from anchor tags, but they contain multiple tags with no class within them. The structure appears as follows. <div c ...

Issue with md-stretch-tabs in Angular-Material causing a problem

I am in the process of developing an Angular-based application. ISSUE: I included md-stretch-tabs in my md-tabs element, but when I switch to tab#2, the tab retracts as if there is not enough space to flex. Is this problem related to dependencies or the c ...

Retrieving data from a radgrid with the power of jQuery

Trying to extract the text from the label GetName in a radgrid using jQuery. Need to iterate through each record to check the value of the label. Can anyone provide assistance? Thanks! Below is the code for my radgrid. <telerik:RadGrid ID="Gridview1 ...

An error occurred while trying to load the configuration "next/core-web-vitals" for extension

If you're embarking on a new project using NextJs and TypeScript, chances are you may encounter the following error: Failed to load config "next/core-web-vitals" to extend from. Wondering how to resolve this issue? ...

What is the best way to utilize await in promises instead of using then?

How can I correctly handle the Promise.all() method? I'm experiencing issues with resolving the promise that generates a series of asynchronous requests (simple database queries in supabase-pg SQL). After iterating through the results with a forEach l ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...

What is the best way to structure a hierarchy in an array or object data using Node.js?

I have the following data arrangement: [{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-1',Town: 'LA-1,LA-1a,LA_AZ_A',Area: 'Area 51'}, { Country: 'USA', State: 'CA&ap ...

Retrieving data from the firebase database by filtering based on the child's specific value

Looking at the firebase database, I can see that only the 'name' field is available. Now, I am trying to retrieve the 'quantity' value associated with that specific 'name'. Can someone provide me with a sample firebase query i ...

Strategies for streamlining repetitive code within a closure in Angularjs

We are currently utilizing Angularjs 1x and I am in the process of refactoring some repetitive code within an Angularjs filter. However, I am facing challenges in getting it to function correctly. It should be a straightforward task. Our standard approach ...

Querying data conditionally with Angular rxjs

I have a json file that contains multiple arrays structured like this: { A[] B[] C[] ... } This is the query I am using: myFunction():void{ this.apiService.getData() .pipe( map((response: any) => response.A), // to access to the &ap ...

`In what way can I acquire auto-generated identifiers for selected documents?`

I am currently using Vue and Firestore in my project. Below is the code snippet I used to generate a document in the collection: <template> <input type="text" v-model="form.title"> </template> methods: { async sa ...