Using ES6 template strings to generate unique strings
5 years ago
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:
1 2 3 4 5 6 7 8 9 | const generateID = () => { // ... some code to generate and return an ID } const getStringTemplate = () => { return `<element uid="${generateID()}"> <child uid="${generateID()}"></child> </element>` } |
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.