Template Literals Advanced
Advanced template literal techniques
Challenge
Section titled “Challenge”Master template literals for flexible string generation and DSL creation.
Explanation
Section titled “Explanation”Template literals provide more than string interpolation. They support multi-line strings, tagged templates, and expression evaluation.
Basic Template Literals
Section titled “Basic Template Literals”const name = 'John';const age = 30;
// Simple interpolationconst message = `Hello, ${name}! You are ${age} years old.`;console.log(message);
// Expressionsconst calculation = `2 + 3 = ${2 + 3}`;
// Multi-line stringsconst html = ` <div> <h1>${title}</h1> <p>${description}</p> </div>`;
// Nested templatesconst user = { name: 'John', age: 30 };const display = `User: ${`${user.name} (${user.age})`}`;Tagged Templates
Section titled “Tagged Templates”// Tag function receives string parts and expressionsfunction highlight(strings, ...values) { let result = '';
for (let i = 0; i < strings.length; i++) { result += strings[i]; if (i < values.length) { result += `**${values[i]}**`; } }
return result;}
const name = 'John';const age = 30;const output = highlight`Hello ${name}, you are ${age} years old`;console.log(output);// Hello **John**, you are **30** years old
// Escape special charactersfunction escapeHtml(strings, ...values) { const map = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
return strings.reduce((acc, str, i) => { acc += str; if (i < values.length) { const value = String(values[i]).replace(/[&<>"']/g, m => map[m]); acc += value; } return acc; }, '');}
const userInput = '<script>alert("xss")</script>';const safe = escapeHtml`<div>${userInput}</div>`;URL Building
Section titled “URL Building”function url(strings, ...values) { const parts = []; for (let i = 0; i < strings.length; i++) { parts.push(strings[i]); if (i < values.length) { parts.push(encodeURIComponent(values[i])); } } return parts.join('');}
const search = 'JavaScript Guide';const query = url`/search?q=${search}&limit=${10}`;// /search?q=JavaScript%20Guide&limit=10SQL Query Building (with caution!)
Section titled “SQL Query Building (with caution!)”// Note: For real SQL, use parameterized queries!function sql(strings, ...values) { const query = []; for (let i = 0; i < strings.length; i++) { query.push(strings[i]); if (i < values.length) { query.push(`'${values[i]}'`); } } return query.join('');}
const userId = 123;const status = 'active';
// Don't use in production - use prepared statements instead!const query = sql`SELECT * FROM users WHERE id = ${userId} AND status = ${status}`;CSS-in-JS with Tagged Templates
Section titled “CSS-in-JS with Tagged Templates”function css(strings, ...values) { let result = '';
for (let i = 0; i < strings.length; i++) { result += strings[i]; if (i < values.length) { result += values[i]; } }
const styleId = `style-${Math.random().toString(36).substr(2, 9)}`; const style = document.createElement('style'); style.id = styleId; style.textContent = result; document.head.appendChild(style);
return styleId;}
const primaryColor = '#007bff';const css_id = css` .button { background-color: ${primaryColor}; padding: 10px 20px; border: none; cursor: pointer; }`;i18n (Internationalization)
Section titled “i18n (Internationalization)”const translations = { 'en': { greeting: 'Hello', farewell: 'Goodbye' }, 'es': { greeting: 'Hola', farewell: 'Adiós' }};
function i18n(locale) { return function(strings, ...values) { const dict = translations[locale] || translations['en'];
let result = ''; for (let i = 0; i < strings.length; i++) { const str = strings[i].trim(); if (str in dict) { result += dict[str]; } else { result += str; }
if (i < values.length) { result += values[i]; } }
return result; };}
const t_en = i18n('en');const t_es = i18n('es');
console.log(t_en`greeting ${name}`); // Hello Johnconsole.log(t_es`greeting ${name}`); // Hola JohnPerformance Optimization
Section titled “Performance Optimization”// String concatenation vs template literalsconst name = 'John';const age = 30;
// ❌ Slower: Multiple concatenationsconst msg1 = 'Name: ' + name + ', Age: ' + age + ', Status: active';
// ✅ Faster: Template literal (one operation)const msg2 = `Name: ${name}, Age: ${age}, Status: active`;
// For repeated operations, use arrays// ❌ Bad: Template literals in loopfor (let i = 0; i < 1000; i++) { document.body.innerHTML += `<div>${i}</div>`;}
// ✅ Good: Build string, then update DOM onceconst parts = [];for (let i = 0; i < 1000; i++) { parts.push(`<div>${i}</div>`);}document.body.innerHTML += parts.join('');