How do I put variables inside javascript strings?
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 '
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.