javascriptecmascript-6template-stringstagged-templates

How to interpolate a tagged template string with a dynamic value?


I would like to interpolate a template string (defined elsewhere):

const url = `www.example.com/${query}/current.json`;

with a dynamic value (for example, "es6") into this:

"www.example.com/es6/current.json"

For example, if i had something like this:

function makeRequest(url, query){
  // how do I generate my final url, here from the url and query?
}

// somehwere else:
makeRequest(url, query)

Is tagged template strings and a tag function the way to go? I've seen many different examples but none that fit this particular situation.


Solution

  • This is exactly the reason functions were invented!

    const dynamicUrl = query => `www.example.com/${query}/current.json`
    
    console.log(dynamicUrl('es6')) //=> 'www.example.com/es6/current.json'