长,单行ES6字符串文字

时间:2016-02-16 09:01:11

标签: javascript ecmascript-6

谷歌充满了博客文章和答案,质疑如何从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字符串?

2 个答案:

答案 0 :(得分:22)

您可以使用\使用字符串换行。换行符(\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

答案 1 :(得分:3)

只需添加到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