1

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?

3 Answers 3

2

Try this::

const message = `[${new Date().toLocaleString()}] ` 
  + response.data.message
  + "\n-----------------\n\n";
this.errors = message + this.errors;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.