【问题标题】:Template Strings ES6 prevent line breaks模板字符串 ES6 防止换行
【发布时间】:2016-10-26 07:42:49
【问题描述】:

我有一个长字符串,我使用 ES6 模板字符串构建它,但我希望它没有换行符:

var string = `As all string substitutions in Template Strings are JavaScript
              expressions, we can substitute a lot more than variable names.
              For example, below we can use expression interpolation to 
              embed for some readable inline math:`

console.log(string);

结果:

As all string substitutions in Template Strings are JavaScript
expressions, we can substitute a lot more than variable names.
For example, below we can use expression interpolation to
embed for some readable inline math:

我的期望:

As all string substitutions in Template Strings are JavaScript expressions, we can substitute a lot more than variable names. For example, below we can use expression interpolation to embed for some readable inline math:

【问题讨论】:

标签: javascript ecmascript-6 template-strings


【解决方案1】:

虽然这不是模板字符串的典型用法,但值得一提。你可以只使用字符串插值,就这么简单


const str = `some long text on ${
    "multiple" } lines without any extra ${
    "spaces" } or line breaks and readable.`;

console.log(str);
// "some long text on multiple lines without any extra spaces or line breaks and readable."

【讨论】:

    【解决方案2】:

    这太疯狂了。

    这里几乎每一个答案都建议运行一个函数 runtime 以便格式化,buildtime 格式错误的文本 oO 我是唯一一个对此事实感到震惊的人吗?尤其是性能影响???

    正如@dandavis 所说,official solution(顺便说一句,这也是 unix shell 脚本的历史解决方案)是用转义字符转义回车:\

    `foo \
    bar` === 'foo bar'
    

    过程简单、高性能、官方、可读、类shell

    【讨论】:

    • 这行得通,你正在逃避回车,而不是进一步的空间
    • 不需要“更多空格”或“代码缩进”。 “这样做的方法”不是这样做,而是遵循代码标准。您在代码编辑器中看到的常见方式(即自动返回到行的那些)不是像上一行那样重新缩进,而是转到行,就是这样(0缩进)。如果你真的想缩进它,去试试,HTML 无论如何只打印一个转义字符。如果您真的不想使用 x espace 字符,即使 HTML 会自动解析它,也请使用执行此操作的工具预处理您的代码,但请不要为了上帝的缘故在运行时运行它
    • 运气不好。
    • 使用 VScode 这将创建一个选项卡式空间...
    【解决方案3】:

    在 ES6 中,我更喜欢在此处使用两个最佳答案的组合(\.replace() 组合)。将替换功能与转义字符相结合的好处意味着您可以使代码块的格式与其余代码保持一致。

    /\s{2}/g 是一个正则表达式,用于选择两个或多个背靠背空格的任何实例。

    const myMessage = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id urna \
        ligula. Suspendisse lobortis ex ut vestibulum venenatis. Donec imperdiet ante odio, \
        nec malesuada diam tristique eget. Lorem ipsum dolor sit amet, consectetur adipiscing \
        elit. Cras in vulputate tellus.`
      .replace(/\s{2,}/g, "");
    

    这会输出一个简单的、完整的字符串。

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id urna ligula. Suspendisse lobortis ex ut vestibulum venenatis. Donec imperdiet ante odio, nec malesuada diam tristique eget. Lorem ipsum dolor sit amet, consectetur elit. Cras在 vulputatetellus 中。”

    【讨论】:

      【解决方案4】:

      对于段落,您可以使用\s+ 正则表达式将空白运行替换为单个空格,以便它适用于换行符和缩进。因此,在您的情况下,只需在末尾添加 .replace(/\s+/gm, ' ')

      var string = `As all string substitutions in Template Strings are JavaScript
                    expressions, we can substitute a lot more than variable names.
                    For example, below we can use expression interpolation to 
                    embed for some readable inline math:`.replace(/\s+/gm, ' ');
      
      console.log(string);
      

      【讨论】:

        【解决方案5】:
        • 要么配置 IDE 进行包装,要么使用模板字符串 1-liner,就像在你的第一个代码 sn-p 中一样。

        • 在换行符之前使用 \ 转义文字字符。

          示例:

          const string = `1st line\
          2nd line\ 
          3rd line`; 
          

          但它不会让您免于空间对齐问题。

        • 要么使用带有 '+' 的老式 ES5 连接。

          示例:

          const string = '1st line' + 
                         '2nd line' + 
                         '3rd line'; 
          
        • 要么对模板空字符串 var ${''} 使用 hack:

          示例:

          const string = `1st line${'' 
                         }2nd line${'' 
                         }3rd line`;
          

        第一种方法更好,原因:

        • 更少的符号(大小方面)
        • 无运行时操作(性能方面)

        【讨论】:

        • 这是这里最聪明的答案。去接受这个
        【解决方案6】:

        如果你有 ES6,你可以使用标签。比如the stripIndent tag from the common-tags library:

        通过以下方式安装:

        npm install common-tags --save
        

        要求通过:

        const stripIndent = require('common-tags/lib/stripIndent')
        

        用作:

        stripIndent`
          As all string substitutions in Template Strings are JavaScript
          expressions, we can substitute a lot more than variable names.
          For example, below we can use expression interpolation to
          embed for some readable inline math:        
        `
        

        编辑:如 cmets 中所述,您可能需要选择:const oneLine = require('common-tags/lib/oneLine') 标记以获得所需的结果。

        有关上述通用标签链接以及this blog的更多信息

        【讨论】:

        • +1 用于库并提及 ES6 标签。但是,在这种情况下,我认为 OP 需要来自 common-tags 库的 oneLine 标记。
        • 运行运行时函数以进行代码格式化... 否决。虽然这个库非常有用,但感谢分享;对于这个特殊用例,他说他“使用 es6 模板构建字符串”,意思是构建时间.. 性能影响?
        【解决方案7】:

        换行符就是换行符...如果您手动生成它们,我发现您可以在运行时获取它们。

        顺便说一句,我现在找到了三种解决方法:

        1. 将您的 IDE 或代码编辑器配置为自动换行,这样如果您不需要它们,您就无需在代码中添加换行符:您的编辑器会将您的代码分成两行或多行,如果每行代码语句超出了配置的最大字符数。

        2. String.prototype.replace删除换行符:

        var string = `因为模板字符串中的所有字符串替换都是 JavaScript 表达式,我们可以替换的不仅仅是变量名。 例如,下面我们可以使用表达式插值来 嵌入一​​些可读的内联数学:`.replace(/\n/gm,"");

        注意:这里您正在运行一个函数 runtime 来格式化您的 buildtime 代码,这可能看起来像一种反模式,并且会影响性​​能

        1. 使用串联执行这些代码换行符:
        var string = `因为模板字符串中的所有字符串替换都是 JavaScript` + `表达式,我们可以替换的不仅仅是变量名。` + `例如下面我们可以使用表达式插值来` + `嵌入一些可读的内联数学:`;

        就我而言,我会选择 #1 选项。

        【讨论】:

        • 第二个例子不能正常工作。线条之间有很大的间隙。
        • @dannyid 你说的大差距是什么意思?它是否包含比换行符更多的字符?
        • @MatíasFidemraizer,将您的 #2 复制/粘贴到控制台中,然后运行 ​​string。你得到了字符串,但是Javascriptexpressionsnames.For example等之间有很多空格。
        • 您可能在浏览器中看不到它,因为浏览器通常会删除多余的空格,但实际的底层数据是不正确的。
        • @dannyid 哦,我明白了,顺便说一句,这是字符串本身的问题,而不是方法。无论如何,我会更新我的答案来解决这个问题
        【解决方案8】:

        我个人更喜欢加入数组的外观:

        var string = [
          `As all string substitutions in Template Strings are JavaScript`,
          `expressions, we can substitute a lot more than variable names.`,
          `For example, below we can use expression interpolation to`,
          `embed for some readable inline math:`
        ].join(' ');
        

        【讨论】:

        • 此方法也比使用+ 的串联更快,因为这只会为整个集合创建一个内部StringBuilder,而不是为每个串联创建一个(尽管这是一个微优化)
        • 运行运行时函数以进行代码格式化... 否决。性能影响?
        • @CyrilCHAPON 的性能真的会阻碍用户体验,以至于这段代码的可读性值得反对吗?
        • 想象一下,对于 10000 个字符串,您有答案
        • 换种说法,这更像是一种“概念异端”,即我所指的做法本身。从概念上讲,这绝对是一种不好的做法,人们可以简单地学习为正确的事情使用正确的工具。 IDE 配置用于“他们作为开发人员所看到的”、转译器和预处理器,以制作构建时用途的东西,并将运行时留给......运行时的东西。
        猜你喜欢
        • 2018-03-04
        • 2015-09-14
        • 2016-09-19
        • 2015-02-18
        • 2018-01-23
        • 1970-01-01
        • 2017-10-03
        相关资源
        最近更新 更多