12

In python, I can do the following:

name = "bob"

print("Hey, %s!" % name)

Is there anything similar to that (or Python's .format()) in JavaScript/NodeJS?

  • Duplicate of http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format – ubik May 28 '12 at 17:36
  • You may consider using CoffeeScript it uses whitespace for block delimition like Python and has also list comprehensions. It doesn't provide string formatting but you can interpolate e.g. console.log("Hey, #{name}!") – denysonique May 29 '12 at 02:19

3 Answers3

15

You can use util.format, it's printf like function.

Alex Ivasyuv
  • 8,585
  • 17
  • 72
  • 90
6

Another option is template strings

For example:

const name = "bob";
console.log(`Hey, ${name}!`);
nickool
  • 834
  • 11
  • 11
2

sprintf should do what you are asking for I think.

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
  • 1
    But that just prints it, doesn't it? What if I want to do something like `socket.send("NOTICE #channel :My name is %s" %(bot.name));`? –  May 28 '12 at 17:44
  • No? I didn't think so I thought it returned a string – Jakob Bowyer May 28 '12 at 17:45
  • 1
    AFAIK sprintf is not part of node. It used to be a package, deprecated now. Answer by @Alex below should be considered valid. – Overdrivr Oct 27 '17 at 13:01
  • The link is broken. This one should work: https://www.npmjs.com/package/sprintf-js – Guigreg Oct 08 '20 at 22:08