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

Commit

Permalink
Improve util.format() compatibility with browser.
Browse files Browse the repository at this point in the history
Fixes #1434.
  • Loading branch information
koichik committed Aug 8, 2011
1 parent 24a1f6e commit d439c09
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
5 changes: 3 additions & 2 deletions doc/api/util.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ argument. Supported placeholders are:
* `%j` - JSON.
* `%%` - single percent sign (`'%'`). This does not consume an argument.

If the placeholder does not have a corresponding argument, `undefined` is used.
If the placeholder does not have a corresponding argument, the placeholder is
not replaced.

util.format('%s:%s', 'foo'); // 'foo:undefined'
util.format('%s:%s', 'foo'); // 'foo:%s'

If there are more arguments than placeholders, the extra arguments are
converted to strings with `util.inspect()` and these strings are concatenated,
Expand Down
4 changes: 3 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ exports.format = function(f) {

var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
Expand All @@ -44,7 +46,7 @@ exports.format = function(f) {
return x;
}
});
for (var len = args.length, x = args[i]; i < len; x = args[++i]) {
for (var x = args[i]; i < len; x = args[++i]) {
if (x === null || typeof x !== 'object') {
str += ' ' + x;
} else {
Expand Down
9 changes: 9 additions & 0 deletions test/simple/test-util-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@ assert.equal(util.format('%j', '42'), '"42"');

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

assert.equal(util.format('%s'), '%s');
assert.equal(util.format('%s', undefined), 'undefined');
assert.equal(util.format('%s', 'foo'), 'foo');
assert.equal(util.format('%s:%s'), '%s:%s');
assert.equal(util.format('%s:%s', undefined), 'undefined:%s');
assert.equal(util.format('%s:%s', 'foo'), 'foo:%s');
assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar');
assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz');

0 comments on commit d439c09

Please sign in to comment.