2

Is there a way to access the formatted string from a console log with formatting specifiers?

https://console.spec.whatwg.org/#formatter

Given the following log message:

console.log('message with %s formatting specifiers %i', 'various', '01');

I would like the following string made available to be used later in the application:

message with various formatting specifiers 1
1

2 Answers 2

1

I can't find documentation for this, but it appears to be built into console.log now: console.log( "native %s", "support" )

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

Comments

0

There is a great String.prototype.printf() function that i've found off a website for this purpose. It is similar to what you want to achieve. This is the whole prototype that you want to add to your javascript page.

String.prototype.printf = function (obj) {
  var useArguments = false;
  var _arguments = arguments;
  var i = -1;
  if (typeof _arguments[0] == "string") {
    useArguments = true;
  }
  if (obj instanceof Array || useArguments) {
    return this.replace(/\%s/g,
    function (a, b) {
      i++;
      if (useArguments) {
        if (typeof _arguments[i] == 'string') {
          return _arguments[i];
        }
        else {
          throw new Error("Arguments element is an invalid type");
        }
      }
      return obj[i];
    });
  }
  else {
    return this.replace(/{([^{}]*)}/g,
    function (a, b) {
      var r = obj[b];
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    });
  }
};

After you've included it, this line of code returns Hello I am foo bar

console.log("Hello I am " + "%s %s".printf(["foo", "bar"])); //returns foo bar

Please see here for more info

If you are using Node.JS

If you're using Node.js, you can require util node module, and use util.format() function. Please see the code down below.

var util = require('util');

console.log(util.format('Hi %s', 'Jack'));
//returns Hi Jack

2 Comments

Thanks - The node.js library will be sufficient for us as a pre-step since it supports the same formatter options as console.
Thank you too :) @Andrew

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.