String interpolation expressions
Basic Concepts of String Interpolation
ECMAScript 6 introduced template string syntax, one of its most important features being string interpolation expressions. This syntax uses backticks (``) to enclose string content and embeds variables or expressions within the string via the ${expression}
format.
const name = '张三';
const greeting = `你好,${name}!`;
console.log(greeting); // Output: 你好,张三!
Syntax Details of Interpolation Expressions
The ${}
interpolation expression can contain any valid JavaScript expression, including:
- Variable references
- Arithmetic operations
- Function calls
- Object property access
- Ternary operators, etc.
const a = 5;
const b = 10;
console.log(`五加十等于${a + b},而不是${2 * (a + b)}。`);
// Output: 五加十等于15,而不是30。
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
const city = 'beijing';
console.log(`欢迎来到${capitalize(city)}!`);
// Output: 欢迎来到Beijing!
Handling Multi-line Strings
Traditional JavaScript strings require explicit use of \n
for line breaks, whereas template strings can directly preserve line break formatting:
// ES5 approach
var oldWay = '第一行\n' +
'第二行\n' +
'第三行';
// ES6 approach
const newWay = `第一行
第二行
第三行`;
Advanced Functionality of Tagged Templates
Template strings can be combined with functions to form the advanced "tagged template" feature:
function highlight(strings, ...values) {
let result = '';
strings.forEach((str, i) => {
result += str;
if (i < values.length) {
result += `<span class="highlight">${values[i]}</span>`;
}
});
return result;
}
const name = '李四';
const age = 28;
const output = highlight`姓名:${name},年龄:${age}`;
console.log(output);
// Output: 姓名:<span class="highlight">李四</span>,年龄:<span class="highlight">28</span>
Usage of Nested Templates
Template strings can be nested to achieve more complex string construction:
const isLargeScreen = false;
const isCollapsed = true;
const classes = `header ${
isLargeScreen ? '' : `icon-${
isCollapsed ? 'expander' : 'collapser'
}`
}`;
console.log(classes); // Output: header icon-expander
Accessing Raw Strings
The String.raw
tag or the raw
property of the function's first parameter can be used to access raw strings (without processing escape characters):
const path = String.raw`C:\Development\profile\about.html`;
console.log(path); // Output: C:\Development\profile\about.html
function showRaw(strings) {
console.log(strings.raw[0]);
}
showRaw`第一行\n第二行`; // Output: 第一行\n第二行
Performance Considerations and Best Practices
While template strings offer convenience, certain scenarios require attention:
- Avoid repeatedly creating the same template strings in loops
- For complex logic, pre-calculate variables before insertion
- Security considerations: Direct insertion of user input may lead to XSS attacks
// Not recommended
function renderItems(items) {
let html = '';
items.forEach(item => {
html += `<div class="item">${item.name}</div>`;
});
return html;
}
// Recommended
function renderItemsBetter(items) {
return items.map(item => `<div class="item">${item.name}</div>`).join('');
}
Integration with Other Language Features
Template strings work well with other ES6+ features:
// Combined with destructuring assignment
const person = { name: '王五', age: 30 };
const { name, age } = person;
console.log(`姓名:${name},年龄:${age}`);
// Combined with arrow functions
const greet = (who) => `你好,${who}!`;
console.log(greet('赵六'));
// Combined with default parameters
function createLink(url = '#', text = '链接') {
return `<a href="${url}">${text}</a>`;
}
Practical Application Examples
- Dynamically generating HTML content:
const products = [
{ id: 1, name: '手机', price: 2999 },
{ id: 2, name: '笔记本', price: 5999 }
];
function renderProductList(products) {
return `
<ul class="product-list">
${products.map(product => `
<li data-id="${product.id}">
<h3>${product.name}</h3>
<p>价格:¥${product.price.toFixed(2)}</p>
</li>
`).join('')}
</ul>
`;
}
- Generating SQL queries:
function buildQuery(table, fields = '*', conditions = {}) {
const whereClause = Object.keys(conditions).length
? `WHERE ${Object.entries(conditions)
.map(([key, val]) => `${key} = ${typeof val === 'string' ? `'${val}'` : val}`)
.join(' AND ')}`
: '';
return `SELECT ${fields} FROM ${table} ${whereClause}`;
}
console.log(buildQuery('users', 'id, name', { status: 1 }));
// Output: SELECT id, name FROM users WHERE status = 1
Browser Compatibility and Transpilation Solutions
While modern browsers generally support template strings, tools like Babel can be used for transpilation when older browser support is needed:
- Original ES6 code:
const name = '张三';
const message = `你好,${name}!`;
- Transpiled ES5 code:
var name = '张三';
var message = '你好,' + name + '!';
When configuring Babel, ensure the @babel/plugin-transform-template-literals
plugin is included.
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn