Reputation: 8424
I have a template string:
function getTemplateString () {
let videoId = 'qwerty'
return `https://player.vimeo.com/video/${videoId}?api=1`
}
I want to store this template string in a const
instead:
const VIMEO_EMBED_URL = `https://player.vimeo.com/video/${videoId}?api=1`
function getTemplateString () {
let videoId = 'qwerty'
// how can I do this next line?
return VIMEO_EMBED_URL.something({videoId: videoId})
}
Can I do string interpolation on constants?
Upvotes: 1
Views: 304
Reputation: 12458
Note that the back-tick quotes are nested in regular quotes.
const VIMEO_EMBED_URL = "`https://player.vimeo.com/video/${videoId}?api=1`";
function getTemplateString() {
let videoId = 'qwerty';
return eval(VIMEO_EMBED_URL);
}
document.write(getTemplateString());
I understand that many uses of eval
, probably including this one, are not recommended. (They introduce possible security concerns, etc.) However, eval
IS part of the language, and some JavaScript experts do discuss how to use it on occasion.
This answer does address the issue raised in the question and does allow the coder to combine the convenient syntax of a template string and the permanence of storing it in a const
. Just understand that it's "User beware".
Upvotes: 1
Reputation: 3156
Template Strings cannot be stored, they return a String when they're defined. So I guess you're looking for a RegExp.
function getTemplateString (url, value) {
return url.replace(/\${video1}/g, value)
}
Other option could be a function that applies the template:
function getTemplateString (videoId) {
return `https://player.vimeo.com/video/${videoId}?api=1`
}
Upvotes: 2