Store a string interpolation template into a variable

52 views Asked by At

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
2

There are 2 answers

0
Moti On BEST ANSWER

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)
0
IceCode On

You would want to write a function for it like the following:

function myStr(input1, input2) {
    return `http://website.com/${input1}/${input2}`;
}

myStr('abc', 'def');