开发者

Is there a sprintf equivalent for node.js

Looking to do output formatting (sprintf type functionality) in node.js, but before I write it myself I was开发者_C百科 wondering if there's something similar built-in (I've trawled the docs to no avail) or if someone's already written a module.

Many thanks


There is now printf-like support in util.format().

Example:

util.format('hello %s', 'world');
// Returns: 'hello world'


There are couple in the npm registry which are actual sprintf implementations since util.format has just a very basic support.

  • sprintf (deprecated now)
  • sprintf-js
  • fast-printf


Here is the javascript version of sprintf:

http://phpjs.org/functions/sprintf:522


console.log works fine.

console.log('%d hours', 4); // 4 hours
console.log('The %2$s contains %1$d monkeys', 4, 'tree'); // The tree contains 4 monkeys


Use locutus

As of now, there is a package that translate functions of other languages to Javascript such as php, python, ruby etc.

const sprintf = require("locutus/php/strings/sprintf")
const data = sprintf("%01.3f", 2);
console.log(data)
//output: 2.000

Try it here codesandbox

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜