Mathias Hillmann
Mathias Hillmann

Reputation: 1837

Concatenating at start of string inside of loop

I have the following code which concatenates to the end of the string "errors":

this.errors += `[${new Date().toLocaleString()}] `;
this.errors += response.data.message;
this.errors += "\n-----------------\n\n";

Which generates the following string:

[30/12/2020 14:48:00] Error 1
-----------------

[30/12/2020 14:49:10] Error 2
-----------------

However I need to concatenate at the start of the string so the most recent error is always at the top:

[30/12/2020 14:49:10] Error 2
-----------------

[30/12/2020 14:48:00] Error 1
-----------------

How can I achieve this?

Upvotes: 1

Views: 43

Answers (3)

choz
choz

Reputation: 17898

One could just utilize an array to store the errors.

const errors = [];

function addError(message) {
  errors.unshift(`${new Date().toLocaleString()} ${message}`);
}

function displayErrors() {
  console.log(errors.join("\n-----------------\n\n"));
}

addError("Error 1");
addError("Error 2");
addError("Error 3");
displayErrors();

Upvotes: 0

Gerard H. Pille
Gerard H. Pille

Reputation: 2578

this.errors = "\n-----------------\n\n" + this.errors;
this.errors = response.data.message + this.errors;
this.errors = `[${new Date().toLocaleString()}] ` + this.errors;

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28434

Try this::

const message = `[${new Date().toLocaleString()}] ` 
  + response.data.message
  + "\n-----------------\n\n";
this.errors = message + this.errors;

Upvotes: 2

Related Questions