skip to Main Content

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

Answers


  1. 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');
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search