Skip to content Skip to sidebar Skip to footer

How To Force Console.log To Always Print Quotes Around Strings

In Chrome at least, if I encounter the following two statements, I get different output depending on the context of the argument. console.log(1,'1') → 1 '1' console.log('test','2

Solution 1:

You can force all arguments to be handled consistently by starting off the log with an empty string:

console.log("", 1, "1") → 11
console.log("", "test", "2") → test 2

Interestingly nodejs has the same logging behavior so it must be standard. The first argument of a console.log() supports varies format strings so it may be a weird consequence of that.

Solution 2:

You can always build your own wrapper function - looks like console.log isn't necessarily consistent across browsers, but you can simplify it, maybe something like:

functionconsole_log() {
    var output = "";
    if (arguments) {
        var i;
        for (i = 0; i < arguments.length; ++i) {
            if (i > 0) {
                output += " ";
            }
            if (arguments[i] && typeofarguments[i] === "string") {
                output += JSON.stringify(arguments[i]);
            } else {
                output += arguments[i];
            }
        }
    }
    console.log(output);
}

console_log("a", 1);
console_log(1, "a");

Of course, modify this to suit your needs.

Solution 3:

I suggest you to use typeof for a more robust solution. Consoles aren't to be trusted!

typeof"2" == 'string'// returns true typeof2 == 'number'// returns true

Post a Comment for "How To Force Console.log To Always Print Quotes Around Strings"