0

Is there a way to store the result of a substitution parameter/string? For example, I want to store the following output into a variable.

console.log('%j', {foo: 123, bar: 'abc'});

Output:

{"foo":123,"bar":"abc"}

I already know JSON.stringify e.g.

const s = JSON.stringify({foo: 123, bar: 'abc'});
Beginner
  • 164
  • 9
  • 3
    *"I already know JSON.stringify"* - then what's not working? – Spectric Aug 16 '21 at 16:16
  • @Spectric - Instead of using `+` multiple times, I want to do something like `'%s %j %s'`. – Beginner Aug 16 '21 at 16:18
  • Take a look at [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) and [this question](https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format) – A_A Aug 16 '21 at 16:21
  • @Thanks, A_A. I solved it exactly this way. – Beginner Aug 16 '21 at 16:26

2 Answers2

0

You can use %o and you can see more details, other operators, in console.log following link: https://developer.mozilla.org/en-US/docs/Web/API/console

console.log('test %o test', {foo: 123, bar: 'abc'});
muhammed ikinci
  • 587
  • 1
  • 5
  • 18
0

I have solved it this way:

const x = 'json';
const y = 'string';
const s = `${JSON.stringify({foo: 123, bar: 'abc'})} is a ${x} ${y}`;
console.log(s);
Beginner
  • 164
  • 9