阿里云主机折上折
  • 微信号
Current Site:Index > Basic template string syntax translates this sentence into English, directly outputting plain text without any additional content.

Basic template string syntax translates this sentence into English, directly outputting plain text without any additional content.

Author:Chuan Chen 阅读数:14039人阅读 分类: JavaScript

Basic Syntax of Template Literals

ECMAScript 6 introduced template literals, denoted by backticks (`). Compared to traditional strings, template literals support multiline text and embedded expressions.

const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!

Multiline Strings

Template literals can directly include line breaks without the need for escape characters or string concatenation.

const multiLine = `
  This is a
  multi-line
  string.
`;
console.log(multiLine);

Expression Interpolation

The ${expression} syntax allows embedding any valid JavaScript expression within the string.

const a = 5;
const b = 10;
console.log(`The sum is ${a + b}`); // Output: The sum is 15

Tagged Templates

Template literals can follow a function name, which will be called to process the template string. This is known as a "tagged template."

function highlight(strings, ...values) {
  let result = '';
  strings.forEach((string, i) => {
    result += string;
    if (i < values.length) {
      result += `<strong>${values[i]}</strong>`;
    }
  });
  return result;
}

const name = 'Bob';
const age = 25;
const message = highlight`Hello, ${name}! You are ${age} years old.`;
console.log(message); // Output: Hello, <strong>Bob</strong>! You are <strong>25</strong> years old.

Raw Strings

String.raw can be used to obtain the raw form of a template literal, ignoring escape characters.

const path = String.raw`C:\Development\profile\about.html`;
console.log(path); // Output: C:\Development\profile\about.html

Nested Templates

Template literals can be nested to achieve more complex string-building logic.

const isLargeScreen = false;
const isCollapsed = true;

const classes = `header ${
  isLargeScreen ? '' : `icon-${isCollapsed ? 'expander' : 'collapser'}`
}`;
console.log(classes); // Output: header icon-expander

Template Literals and HTML

Template literals are particularly well-suited for generating HTML fragments, maintaining code readability.

const items = ['apple', 'orange', 'banana'];
const html = `
  <ul>
    ${items.map(item => `<li>${item}</li>`).join('')}
  </ul>
`;
console.log(html);

Performance Considerations

While template literals offer convenience, excessive use in performance-sensitive scenarios may impact performance.

// Less performant approach
let html = '';
for (let i = 0; i < 1000; i++) {
  html += `<div>${i}</div>`;
}

// Better approach
const elements = [];
for (let i = 0; i < 1000; i++) {
  elements.push(`<div>${i}</div>`);
}
html = elements.join('');

Limitations of Template Literals

Template literals are powerful but have some limitations to note:

  1. Cannot directly use undefined variables
  2. Overly complex expressions can reduce readability
  3. Some IDEs may have limited support for nested templates
// Using undefined variables will throw an error
try {
  console.log(`Value: ${undefinedVariable}`);
} catch (e) {
  console.error(e); // ReferenceError
}

Template Literals and Internationalization

Template literals can easily integrate with internationalization libraries.

const messages = {
  en: {
    greeting: name => `Hello, ${name}!`
  },
  es: {
    greeting: name => `¡Hola, ${name}!`
  }
};

function localize(lang, key, ...args) {
  return messages[lang][key](...args);
}

console.log(localize('es', 'greeting', 'Carlos')); // Output: ¡Hola, Carlos!

Advanced Usage of Template Literals

Combining with Proxy enables dynamic template literal processing.

const templateCache = new Map();

function template(strings, ...keys) {
  return function(...values) {
    const cacheKey = strings.join('');
    if (templateCache.has(cacheKey)) {
      return templateCache.get(cacheKey)(...values);
    }
    
    const result = strings.reduce((acc, str, i) => {
      return acc + str + (values[keys[i]] || '');
    }, '');
    
    templateCache.set(cacheKey, () => result);
    return result;
  };
}

const t = template`${0} + ${1} = ${2}`;
console.log(t(1, 2, 3)); // Output: 1 + 2 = 3

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.