How do I put variables inside javascript strings?
if you are using ES6, the you should use the Template literals.
//you can do this
let sentence = `My name is ${ user.name }. Nice to meet you.`
read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
With Node.js v4
, you can use ES6's Template strings
var my_name = 'John';
var s = `hello ${my_name}, how are you doing`;
console.log(s); // prints hello John, how are you doing
You need to wrap string within `
(backtick) instead of '
(apostrophe)
util.format does this.
It will be part of v0.5.3 and can be used like this:
var uri = util.format('http%s://%s%s',
(useSSL?'s':''), apiBase, path||'/');
Note, from 2015 onwards, just use backticks for templating
https://stackoverflow.com/a/37245773/294884
let a = `hello ${name}` // NOTE!!!!!!!! ` not ' or "
Note that it is a backtick, not a quote.
If you want to have something similar, you could create a function:
function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;
return str.replace(/%s/g, () => args[i++]);
}
Usage:
s = parse('hello %s, how are you doing', my_name);
This is only a simple example and does not take into account different kinds of data types (like %i
, etc) or escaping of %s
. But I hope it gives you some idea. I'm pretty sure there are also libraries out there which provide a function like this.