Variables are replaced at the time the literal is evaluated, so you cannot create a universal template that can be replaced with variables later:
var template = `http://example.com/?name=${name}&age=${age}`; var name = "John"; var age = "30"; console.log( template );
Edit: fiddle for those who reuse a console session and have variables defined from previous experiments: https://jsfiddle.net/nwvcrryt/
You also cannot convert the string literal "My name is ${name}"
to a template, like what you are trying to do.
However, you can use a function that takes a name and age and returns the desired URL:
const formatUrl = (name, age) => `http://example.com/?name=${name}&age=${age}`; let name = "John"; let age = "30"; let url = formatUrl( name, age );
pawel source share