【问题标题】:How to interpolate a tagged template string with a dynamic value?如何用动态值插入标记的模板字符串?
【发布时间】:2017-07-16 08:13:38
【问题描述】:

我想插入一个模板字符串(在别处定义):

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

用一个动态值(例如,“es6”)改成这样:

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

例如,如果我有这样的事情:

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

// somehwere else:
makeRequest(url, query)

标记的模板字符串和标记函数是要走的路吗?我见过很多不同的例子,但没有一个适合这种特殊情况。

【问题讨论】:

  • 你只需要在 {}`www.example.com/${query}/current.json`; 之前加上 $
  • 那么,var query = 'es6'?
  • “在别处定义”是什么意思?你可能会混淆template literals with templates
  • 抱歉,我不是很清楚 - 刚刚编辑了帖子

标签: javascript ecmascript-6 template-strings tagged-templates


【解决方案1】:

这正是发明函数的原因!

const dynamicUrl = query => `www.example.com/${query}/current.json`

console.log(dynamicUrl('es6')) //=> 'www.example.com/es6/current.json'

【讨论】:

  • @zok 不要忘记 encodeURIComponent(query) 或确保 query 是 URL 安全的。
猜你喜欢
  • 1970-01-01
  • 2018-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多