Search code examples
javascriptstringstring-interpolation

Store a string interpolation template into a variable


Is there a way to store a string interpolation template into a variable in JavaScript and just call it as a function (or something like this)?

I would like to do something like this:

const myStr = `http://website.com/${0}/${1}`;
console.log(myStr('abc','def'));

// http://website.com/abc/def

Solution

  • Yes, just use an anonymous function, e.g.

    const myStr = (a, b) => `http://website.com/${a}/${b}`
    

    if you want to use more than one argument just pass it like this

    const myStr = (...args) => `http://website.com/${args.join('/')}`
    myStr(1, 2, 3)