Is there a sprintf equivalent for node.js

Printfnode.js

Printf Problem Overview


Looking to do output formatting (sprintf type functionality) in node.js, but before I write it myself I was 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

Printf Solutions


Solution 1 - Printf

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

Example:

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

Solution 2 - Printf

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

Solution 3 - Printf

Here is the javascript version of sprintf:

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

Solution 4 - Printf

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

Solution 5 - Printf

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteven Mohapi-BanksView Question on Stackoverflow
Solution 1 - PrintflapoView Answer on Stackoverflow
Solution 2 - PrintfKARASZI IstvánView Answer on Stackoverflow
Solution 3 - PrintfSarfrazView Answer on Stackoverflow
Solution 4 - PrintfJürgen PaulView Answer on Stackoverflow
Solution 5 - Printfßiansor Å. ÅlmerolView Answer on Stackoverflow