0

I tried solution suggested here How to get the console.log content as string in JavaScript

Problem is it's missing the full formatted output : it gives a, b, c instead whereas I'd like to get ["a", "b", "c"] for my case https://jsfiddle.net/eywjn9o8/

var logBackup = console.log;
var logMessages = [];

console.log = function() {
    logMessages.push.apply(logMessages, arguments);
    logBackup.apply(console, arguments);
};

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
alert(logMessages)

enter image description here

4
  • 2
    You're alerting the array, which calls toString() on it implicitly. Certainly not what you're looking for. Use logBackup(logMessages); instead and it'll be closer to the actual console output. Or use alert(JSON.stringify(logMessages[0])) Commented Oct 9, 2021 at 12:27
  • @ChrisG post it as answer? Commented Oct 9, 2021 at 12:28
  • 1
    @Cid Certainly not Commented Oct 9, 2021 at 12:29
  • Duplicate: JavaScript print array to string with brackets and quotes Commented Oct 9, 2021 at 12:31

1 Answer 1

1

Firefox and Google Chrome now have a built-in JSON object, so you can just say alert(JSON.stringify(logMessages)). This is not part of the Javascript language spec, so you shouldn't rely on the JSON object being present in all browsers, but for debugging purposes it's incredibly useful.

Source

Sign up to request clarification or add additional context in comments.

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.