基本模板字符串语法
模板字符串的基本语法
ECMAScript 6 引入了模板字符串,使用反引号(`
)标识。与传统字符串相比,模板字符串支持多行文本和嵌入表达式。
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // 输出: Hello, Alice!
多行字符串
模板字符串可以直接包含换行符,无需使用转义字符或字符串连接。
const multiLine = `
This is a
multi-line
string.
`;
console.log(multiLine);
表达式插值
通过${expression}
语法可以在字符串中嵌入任意有效的JavaScript表达式。
const a = 5;
const b = 10;
console.log(`The sum is ${a + b}`); // 输出: The sum is 15
标签模板
模板字符串可以跟在一个函数名后面,该函数将被调用来处理这个模板字符串,称为"标签模板"。
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); // 输出: Hello, <strong>Bob</strong>! You are <strong>25</strong> years old.
原始字符串
通过String.raw
可以获取模板字符串的原始形式,忽略转义字符。
const path = String.raw`C:\Development\profile\about.html`;
console.log(path); // 输出: C:\Development\profile\about.html
嵌套模板
模板字符串可以嵌套使用,实现更复杂的字符串构建逻辑。
const isLargeScreen = false;
const isCollapsed = true;
const classes = `header ${
isLargeScreen ? '' : `icon-${isCollapsed ? 'expander' : 'collapser'}`
}`;
console.log(classes); // 输出: header icon-expander
模板字符串与HTML
模板字符串特别适合用于生成HTML片段,可以保持代码的可读性。
const items = ['apple', 'orange', 'banana'];
const html = `
<ul>
${items.map(item => `<li>${item}</li>`).join('')}
</ul>
`;
console.log(html);
性能考虑
虽然模板字符串提供了便利,但在性能敏感的场景中,大量使用模板字符串可能影响性能。
// 性能较差的写法
let html = '';
for (let i = 0; i < 1000; i++) {
html += `<div>${i}</div>`;
}
// 更好的写法
const elements = [];
for (let i = 0; i < 1000; i++) {
elements.push(`<div>${i}</div>`);
}
html = elements.join('');
模板字符串的限制
模板字符串虽然强大,但也有一些限制需要注意:
- 不能直接使用未定义的变量
- 过度复杂的表达式会影响可读性
- 某些IDE对嵌套模板的支持可能不完善
// 未定义变量会抛出错误
try {
console.log(`Value: ${undefinedVariable}`);
} catch (e) {
console.error(e); // ReferenceError
}
模板字符串与国际化
模板字符串可以方便地与国际化库结合使用。
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')); // 输出: ¡Hola, Carlos!
模板字符串的高级用法
结合Proxy可以实现动态模板字符串处理。
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)); // 输出: 1 + 2 = 3
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
下一篇:多行字符串的实现