Issue
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
Solution
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
Answered By - turmuka
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.