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?

2
  • Duplicate of stackoverflow.com/questions/610406/… Commented May 28, 2012 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}!") Commented May 29, 2012 at 2:19

3 Answers 3

15

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

Sign up to request clarification or add additional context in comments.

Comments

7

Another option is template strings

For example:

const name = "bob";
console.log(`Hey, ${name}!`);

Comments

2

sprintf should do what you are asking for I think.

4 Comments

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));?
No? I didn't think so I thought it returned a string
AFAIK sprintf is not part of node. It used to be a package, deprecated now. Answer by @Alex below should be considered valid.
The link is broken. This one should work: npmjs.com/package/sprintf-js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.