不打破缩进的多行字符串 [英] Multiline strings that don't break indentation

查看:149
本文介绍了不打破缩进的多行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此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:

这篇关于不打破缩进的多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆