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?
-
Strings are immutable in JavaScript as well. The plus (concatenation) operator makes a new string from pieces of an old one.Joe Simmons– Joe Simmons2013年09月30日 22:31:36 +00:00Commented Sep 30, 2013 at 22:31
-
Are we strictly talking vanilla here? Anyway underscores' templates do a pretty good job at thatraam86– raam862013年09月30日 22:31:48 +00:00Commented Sep 30, 2013 at 22:31
-
possible duplicate of JavaScript equivalent to printf/string.formatNaftali– Naftali2013年09月30日 22:33:20 +00:00Commented Sep 30, 2013 at 22:33
4 Answers 4
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"
3 Comments
${} locations. A single tick would just signify a normal string and would be interpreted as such.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
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.
1 Comment
If for some reason you are doing this many times per second and referencing the strings many times per call, you can always store the strings themselves as variables.
var preX = 'x: '
, preY = 'y: '
, coords
;
coords = preX + x + preY + y;
This of course should be supported by benchmarking/profiling, but creating many strings per frame is often a source of unnecessary garbage which can result in jank down the line.
2 Comments
preX (etc.) variables which could have changed, whereas it is impossible to change a string literal.