tgoneil
tgoneil

Reputation: 1624

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!

Upvotes: 5

Views: 7818

Answers (2)

brentburg
brentburg

Reputation: 106

It doesn't have anything to do with the JSON.stringify. I can reproduce the single % output with node 0.10.36 by just doing console.log('%%'). This is likely an issue with util.format used internally for console.log by node.

https://nodejs.org/docs/latest-v0.10.x/api/util.html#util_util_format_format

However, in node 4.0 I get the expected result.

Upvotes: 2

Freyja
Freyja

Reputation: 40894

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.

Upvotes: 7

Related Questions