diff options
author | koichik <koichik@improvement.jp> | 2011-08-07 15:55:44 +0900 |
---|---|---|
committer | koichik <koichik@improvement.jp> | 2011-08-08 23:24:05 +0900 |
commit | d439c092c20395b601aba9a68807868a85b422aa (patch) | |
tree | 6334ffa346ada0f28a3f4865d82657dfd3c98e91 | |
parent | 24a1f6ecc502ab67ca4aa33aa2af7e67747aad86 (diff) | |
download | node-new-d439c092c20395b601aba9a68807868a85b422aa.tar.gz |
Improve util.format() compatibility with browser.
Fixes #1434.
-rw-r--r-- | doc/api/util.markdown | 5 | ||||
-rw-r--r-- | lib/util.js | 4 | ||||
-rw-r--r-- | test/simple/test-util-format.js | 9 |
3 files changed, 15 insertions, 3 deletions
diff --git a/doc/api/util.markdown b/doc/api/util.markdown index 65e1f7c63e..bf18075dec 100644 --- a/doc/api/util.markdown +++ b/doc/api/util.markdown @@ -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, diff --git a/lib/util.js b/lib/util.js index d4e6bbf5cc..039d0fa028 100644 --- a/lib/util.js +++ b/lib/util.js @@ -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++]); @@ -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 { diff --git a/test/simple/test-util-format.js b/test/simple/test-util-format.js index 6a497089b1..e9c28c2de5 100644 --- a/test/simple/test-util-format.js +++ b/test/simple/test-util-format.js @@ -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'); + |