The following technique is something that I found template strings in ES6 to be quite useful for. I needed to generate XML chunks (as a string) where each node had a unique ID every time the XML was generated.
Most examples of template strings I see around the web just use simple variables inside template strings. I found that you can also use functions that return a value, making the string even more dynamic.
I ended up writing a function that creates the string and inserts unique IDs in specific locations every time the function is called:
const generateID = () => {
// ... some code to generate and return an ID
}
const getUniqueString = () => {
return `id=${generateID()}`
}
getUniqueString(); // "id=dJsdnUSD"
getUniqueString(); // "id=5nd9gHfs"
getUniqueString(); // "id=vn9s8fFQ"
You can place ${generateID()}
any number of times in the template string and in each location a unique ID will be inserted.
Now I can call getStringTemplate() and get a unique chunk of XML every time.