多行字符串,不会破坏缩进

Šim*_*das 32 javascript ecmascript-6 template-strings

根据这个讨论,ECMAScript 6中可以定义多行字符串,而不必将字符串的后续行放在行的最开头.

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`;
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下如何实现这一目标吗?如何定义这个dontIndent东西以删除用于缩进的空格?

Šim*_*das 15

通过定义自定义函数然后将其用作标记(dontIndent上图)来实现此功能.代号打击来自Zenparsing的要点:

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);
}
Run Code Online (Sandbox Code Playgroud)

我已经在Firefox Nightly中成功测试了它:

在此输入图像描述


mik*_*ana 15

2016答案:dedent-js包将处理这个问题.注意'dedent-js'包实际上适用于制表符和空格,'dedent'在制表符上失败:

var dedent = require('dedent-js');

var text = dedent(`
  <div>
    <span>OK</span>
    <div>
      <div></div>
    </div>
  </div>
`);
Run Code Online (Sandbox Code Playgroud)

将剥离每行上的前进空格和前导回车.它还拥有更多用户,问题跟踪器,并且比Stack Overflow的copypasting更容易更新!


Jim*_*yle 14

您也可以只对双空格进行字符串替换(假设您的缩进使用空格,而不是制表符)。显然,实际字符串中的任何双空格都将被删除,但在大多数情况下,这应该没问题。

const MSG = (`Line 1
          line 2
          line 3`).replace(/  +/g, '');
// outputs
/*
Line 1
line 2
line 3
*/
Run Code Online (Sandbox Code Playgroud)

  • 如果添加“^”,即“/^ +/g”,那么它只会删除行前空格。可能需要一个多行标志。 (6认同)

Tom*_*aas 7

如何定义这个dontIndent东西以删除用于缩进的空格?

我想这样的事情应该足以满足许多情况(包括 OP):

function dontIndent(str){
  return ('' + str).replace(/(\n)\s+/g, '$1');
}
Run Code Online (Sandbox Code Playgroud)

此代码段中的演示代码:

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`;

console.log(a);
         
function dontIndent(str){
  return ('' + str).replace(/(\n)\s+/g, '$1');
}
Run Code Online (Sandbox Code Playgroud)

解释

可以使用标签调用JavaScript 模板文字,在本例中为dontIndent. 标签被定义为函数,并以模板文字作为参数被调用,所以我们定义了一个dontIndent()函数。模板文字作为数组中的参数传递,因此我们使用表达式('' + str)将数组内容转换为字符串。然后,我们可以使用正则表达式一样/(\n)\s+/g.replace()换行后跟空格,只有断行的所有匹配,实现OP的目的。