不打破缩进的多行字符串
根据此esdiscuss讨论,ECMAScript 6中可以定义多行字符串,而不需要将字符串的后续行放置在行的开始处。
According to this esdiscuss discussion, it is possible in ECMAScript 6 to define multiline strings without having to place subsequent lines of the string at the very beginning of the line.
Allen Wirfs-Brock的帖子包含代码示例:
var a = dontIndent
`This is a template string.
Even though each line is indented to keep the
code neat and tidy, the white space used to indent
is not in the resulting string`;
有人可以解释一下如何实现吗?如何定义这个 dontIndent
的东西,以便删除用于缩进的空格?
Could someone explain how this can be achieved? How to define this dontIndent
thing in order to remove the whitespace used for indentation?
此功能通过定义自定义函数,然后将其作为标签( dontIndent
)进行实现。代码打击来自 Zenparsing的要点:
This feature is implemented by defining a custom function and then using it as a tag (dontIndent
above). The code blow is from Zenparsing's gist:
function dedent(callSite, ...args) {
function format(str) {
let size = -1;
return str.replace(/\n(\s+)/g, (m, m1) => {
if (size < 0)
size = m1.replace(/\t/g, " ").length;
return "\n" + m1.slice(Math.min(m1.length, size));
});
}
if (typeof callSite === "string")
return format(callSite);
if (typeof callSite === "function")
return (...args) => format(callSite(...args));
let output = callSite
.slice(0, args.length + 1)
.map((text, i) => (i === 0 ? "" : args[i - 1]) + text)
.join("");
return format(output);
}
我已经在Firefox中成功测试了它:
I've successfully tested it in Firefox Nightly: