【问题标题】:Long, single line ES6 string literal长的单行 ES6 字符串字面量
【发布时间】:2016-05-27 11:06:27
【问题描述】:

谷歌上充斥着关于如何从 ES6 字符串文字中受益的博客文章和答案。而且几乎每一篇深入解释这个特性的博文都有一些关于如何实现多行字符串的细节:

let a = `foo
bar`;

但我找不到有关如何实现长单行字符串的任何详细信息,如下所示:

let a = `This is a very long single line string which might be used to display assertion messages or some text. It has much more than 80 symbols so it would take more then one screen in your text editor to view it. Hello ${world}`

任何线索或解决方法,还是应该坚持使用 es3 字符串?

【问题讨论】:

  • 您是否在问应该如何格式化代码以使其仍然是单行但由编辑器显示为多行?这与 JS 或 ES6 无关,这是一些编辑器可以做到的。
  • @SergiuParaschiv 是的,但这仅仅是编辑的责任吗?对于 Python,即 PEP8 样式指南建议不要使用超过 80 个符号的行。 javascript没有这样的指导方针吗?一个人应该如何查看 github 上超过 80 行的代码?
  • 不幸的是,JavaScript 社区没有自己的 PEP8。有各种风格和数百种风格指南。在 GitHub 上你当然可以看到超过 80 行的代码,你只需要滚动。为什么还要写这么长的字符串呢?可能有解决方法。

标签: javascript ecmascript-6


【解决方案1】:

您可以使用\ 用字符串换行。换行符 (\n) 不会出现在字符串本身中。

let a = `This is a very long single line string which might be used \
to display assertion messages or some text. It has much more than \
80 symbols so it would take more then one screen in your text \
editor to view it. Hello ${world}`

注意不要缩进你的字符串,否则缩进会在字符串中:

let a = `Hello\
         World`;

a === 'Hello         World' // true

【讨论】:

    【解决方案2】:

    只是添加到 Gpx 答案:您可以使用 this library 保留缩进。

    import {oneLineTrim} from 'common-tags'
    
    oneLineTrim`
      https://news.com/article
      ?utm_source=designernews.com
    `)
    // https://news.com/article?utm_source=designernews.com
    

    【讨论】:

      猜你喜欢
      • 2017-10-12
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多