How to insert variables in JavaScript strings?

What's the best way to do insert variables in a string in JavaScript? I'm guessing it's not this:

var coordinates = "x: " + x + ", y: " + y;

In Java, Strings are immutable and doing something like the above would unnecessarily create and throw away Strings. Ruby is similar and has a nice way of doing the above:

coordinates = "x: #{x}, y: #{y}"

Does something similar exist for JavaScript?


Introduced in ES6 as "template strings"

MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

const name = "Nick"
const greeting = `Hello ${name}`  // "Hello Nick"

That's fine in JavaScript. There is no good built-in equivalent of an sprintf or String.format, however, you can build your own.

Don't worry about the "unnecessary" string objects. That's definitely micro-optimization. Address it if and when you need that extra tiny bit of performance or memory optimization, but in distributed software, you probably don't.


https://www.npmjs.com/package/stringinject

https://github.com/tjcafferkey/stringinject

I created this function to do exactly this, it will allow you to pass in a string, and an object with keys that will replace placeholder values in the string with their values like below:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

// My username is tjcafferkey on Github