模板字符串
模板字符串``
字符串中可以出现换行符
可以使用 ${xxx} 形式输出变量
优点
在模板字符串中,空格、缩进、换行都会被保留,可以识别html代码
模板字符串完全支持“运算”式的表达式,可以在${}里完成一些计算
1. 模板字符串
需要拼接字符串的时候尽量改成使用模板字符串:
// 例子 2-1
// bad const foo = 'this is a' + example; // good const foo = `this is a ${example}`;
2. 标签模板
可以借助标签模板优化书写方式:
// 例子 2-2
let url = oneLine ` www.taobao.com/example/index.html ?foo=${foo} &bar=${bar} `; console.log(url); // www.taobao.com/example/index.html?foo=foo&bar=bar
function oneLine(template, ...expressions) { let result = template.reduce((prev, next, i) => { let expression = expressions[i - 1]; return prev + expression + next; }); result = result.replace(/(\n\s*)/g, " "); result = result.trim(); return result; }
链接:https://juejin.cn/post/6844903726201700365
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

浙公网安备 33010602011771号