0

I am experienced in Python, but relatively new to the Javascript language. I know in Python, if I want to substitute a variable into a string (for instance) I could do it this way:

s = "%s:%s" % (mins, secs)

However, I can't find an equivalent way to substitute values in Javascript. Does something like this exist, or am I going about this the wrong way?

morgan
  • 13
  • 5

1 Answers1

2

Not available in ES5, but it is available in ES6:

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

Keep in mind this might not work right in the browser across the board-- you'll probably need to use something like Babel to transpile your code to ES5.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
  • 1
    Would you consider [this](http://stackoverflow.com/a/13639670/1832539) relevant as well? My JS is a bit rusty, so not sure if what I linked is also a valid solution. – idjaw Oct 14 '16 at 20:34
  • 1
    @idjaw - sure-- the link you provided is basically a custom solution that this user spun up to handle the case. If for some reason using the ES6 solution was not an option for you, that would certainly be worth exploring as a valid alternative. – Alexander Nied Oct 14 '16 at 20:35
  • Thanks. From my understanding ES6 is *fairly* well supported on a lot of browser versions right now, correct? So, should the ES6 solution be the favoured one here for *most* typical cases? Asking purely as a curious passer by to this question :) – idjaw Oct 14 '16 at 20:43
  • 1
    No sweat-- it'll probably be project specific, to be honest. The linked MDN page in the answer shows that this feature enjoys no support in Internet Explorer yet. Honestly, I imagine the number of people deploying ES6 code _directly to the browser_ is pretty low. The number of people writing in ES6 and transpiling to ES5, though, seems to be steadily on the rise-- there are a lot of great new features in ES6 and browser support is increasing all the time. I would say if your project is already using ES6 and Babel, use this-- otherwise, your solution is probably the preference. – Alexander Nied Oct 14 '16 at 20:47
  • Cheers. Thanks for the info! – idjaw Oct 14 '16 at 20:49