How do I put variables inside javascript strings? (Node.js)


s = 'hello %s, how are you doing' % (my_name)

That's how you do it in python. How can you do that in javascript/node.js?

6/15/2014 8:24:17 AM

Accepted Answer

If you want to have something similar, you could create a function:

function parse(str) {
    var args = [], 1),
        i = 0;

    return str.replace(/%s/g, () => args[i++]);


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.

1/31/2019 4:50:59 AM

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 '

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow