Skip to content

Instantly share code, notes, and snippets.

@leemason
Last active December 7, 2020 15:25
Show Gist options
  • Save leemason/50056e4ac4ca10ac27088464c21ded27 to your computer and use it in GitHub Desktop.
Save leemason/50056e4ac4ca10ac27088464c21ded27 to your computer and use it in GitHub Desktop.
// Existing solution (result not implementation)
const existingWay = theUrlConstructor([ '/api/v1/resource/{0}/{1}', 'my string, with unsafe', 'url +characters+' ])
// /api/v1/resource/my%20string%2C%20with%20unsafe/url%20%2Bcharacters%2B
// New solution
const url = (strings, ...values) => {
return strings.reduce((compiled, string, index) => {
return compiled.concat(string, encodeURIComponent(values[index] || ''))
}, []).join('')
}
const first = 'my string, with unsafe'
const second = 'url +characters+'
const newWay = url`/api/v1/resource/${first}/${second}`
// /api/v1/resource/my%20string%2C%20with%20unsafe/url%20%2Bcharacters%2B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment