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

user310291
  • 36,946
  • 82
  • 271
  • 487
  • 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]))` –  Oct 09 '21 at 12:27
  • @ChrisG post it as answer? – Cid Oct 09 '21 at 12:28
  • 1
    @Cid Certainly not –  Oct 09 '21 at 12:29
  • Duplicate: [JavaScript print array to string with brackets and quotes](https://stackoverflow.com/questions/29956228/javascript-print-array-to-string-with-brackets-and-quotes) –  Oct 09 '21 at 12:31

1 Answers1

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

Gkonst
  • 26
  • 5