Skip to content
This repository was archived by the owner on Apr 22, 2023. It is now read-only.

Commit d439c09

Browse files
committedAug 8, 2011
Improve util.format() compatibility with browser.
Fixes #1434.
·
1 parent 24a1f6e commit d439c09

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed
 

‎doc/api/util.markdown

+3-2
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@ argument. Supported placeholders are:
1717
* `%j` - JSON.
1818
* `%%` - single percent sign (`'%'`). This does not consume an argument.
1919

20-
If the placeholder does not have a corresponding argument, `undefined` is used.
20+
If the placeholder does not have a corresponding argument, the placeholder is
21+
not replaced.
2122

22-
util.format('%s:%s', 'foo'); // 'foo:undefined'
23+
util.format('%s:%s', 'foo'); // 'foo:%s'
2324

2425
If there are more arguments than placeholders, the extra arguments are
2526
converted to strings with `util.inspect()` and these strings are concatenated,

‎lib/util.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ exports.format = function(f) {
3434

3535
var i = 1;
3636
var args = arguments;
37+
var len = args.length;
3738
var str = String(f).replace(formatRegExp, function(x) {
39+
if (i >= len) return x;
3840
switch (x) {
3941
case '%s': return String(args[i++]);
4042
case '%d': return Number(args[i++]);
@@ -44,7 +46,7 @@ exports.format = function(f) {
4446
return x;
4547
}
4648
});
47-
for (var len = args.length, x = args[i]; i < len; x = args[++i]) {
49+
for (var x = args[i]; i < len; x = args[++i]) {
4850
if (x === null || typeof x !== 'object') {
4951
str += ' ' + x;
5052
} else {

‎test/simple/test-util-format.js

+9
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,12 @@ assert.equal(util.format('%j', '42'), '"42"');
4747

4848
assert.equal(util.format('%%s%s', 'foo'), '%sfoo');
4949

50+
assert.equal(util.format('%s'), '%s');
51+
assert.equal(util.format('%s', undefined), 'undefined');
52+
assert.equal(util.format('%s', 'foo'), 'foo');
53+
assert.equal(util.format('%s:%s'), '%s:%s');
54+
assert.equal(util.format('%s:%s', undefined), 'undefined:%s');
55+
assert.equal(util.format('%s:%s', 'foo'), 'foo:%s');
56+
assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar');
57+
assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz');
58+

0 commit comments

Comments
 (0)
This repository has been archived.