Template Literal in JavaScript
在 Template Literal 之前,JavaScript 里的字符串拼接或者模板替换通常有三种做法。
"a" + "b"
- 字符串拼接["a", "b"].join()
- 数组拼接regsub(/\$\{name\}/g, name)
- 正则表达式替换
Long Literal String
let longString = "This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
let longString = "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
Template Literal
s = `hello ${name}. 可以变量替换
可以跨行
${age+3} 可以表达式替换
`;
Tagged Template Literal
默认的 Template Literal 相当于下面带有 tag 的实现。
JavaScript 引擎把模板字符串分割成纯文本的部分,之后连同表达式的结果一起传给函数。
function text(literals){
let i;
let text = literals[0];
for(i=1; i<arguments.length; i++){
text += arguments[i] + literals[i];
}
return text;
}
s = text`<h1>${title}</h1>`
lit-html
function html(literals){
let html = literals[0];
for(let i=1; i<arguments.length; i++){
html += '{{}}' + literals[i];
}
let template = document.createElement("template");
template.innerHTML = html;
let createTreeWalker = document.createTreeWalker;
let walker = createTreeWalker(template.content, NodeFilter.SHOW_ELEMENT);
while(walker.nextNode()) {
console.log(walker.currentNode);
}
return template;
}
template = html`<h1>${title}</h1>`