Search code examples
javascriptjsonstringify

Javascript stringify '%%' loses a percent sign


Why is the output of stringify missing a percent sign?

var a = ["dp",'%%'];
var t = JSON.stringify (a);
console.log ('t: ' + t);

Result is:

t: ["dp","%"]

Why isn't the result:

t: ["dp","%%"]

Thanks!


Solution

  • As specified in the documentation for console.log in Node.js, the function takes arguments in a printf-like way:

    The first argument is a string that contains zero or more placeholders.
    Each placeholder is replaced with the converted value from its corresponding argument. Supported placeholders are:

    %s - String.
    %d - Number (both integer and float).
    %j - JSON. Replaced with the string '[Circular]' if the argument contains circular references.
    %% - single percent sign ('%'). This does not consume an argument.
    If the placeholder does not have a corresponding argument, the placeholder is not replaced.

    Thus, any occurrence of %% in a string printed with console.log in Node.js (not browser) will be replaced by a single %. Any %s, %d or %j will be replaced by a string, number or JSON string, respectively. Here are some examples:

    console.log("This is a string: %s", "Hello, World!");
    //= This is a string: Hello, World!
    
    console.log("This is a number: %d", 3.14);
    //= This is a number: 3.14
    
    console.log("This is a JSON string: %j", { value: true });
    //= This is a JSON string: {"value":true}
    
    console.log("This is a single percentage sign: %%");
    //= This is a single percentage sign: %
    
    console.log("If we use %%s and %%d here we get '%s' and '%d'.", "a string", 100);
    //= If we use %s and %d here we get 'a string' and '100'.
    

    Calling console.log in a browser, however, will just print the plain string with none of the above substitutions.