javascriptstringnode.js

How do I put variables inside javascript strings?


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?


Solution

  • Note, from 2015 onwards, just use backticks for templating

    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.