Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long, single line ES6 string literal

The google is full of blog posts and answers to question how one should benefit from ES6 string literals. And almost every blog post explaining this feature in depth has some details on how to implement multiline strings:

let a = `foo
bar`;

But i can not find any details on how to implement long single line strings like the following:

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

Any clues or workarounds or should a one stick to the es3 strings instead?

like image 615
canufeel Avatar asked Feb 16 '16 09:02

canufeel


People also ask

How do you break a line in template literal?

To escape a backtick in a template literal, put a backslash ( \ ) before the backtick.

What is `` in JS?

Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.

What are string literals ES6?

Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.


2 Answers

You can go on a new line with a string using \. The newline character (\n) will not appear in the string itself.

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

Pay attention not to indent your string though or the indentation will be in the string:

let a = `Hello\
         World`;

a === 'Hello         World' // true
like image 170
Giorgio Polvara - Gpx Avatar answered Sep 22 '22 21:09

Giorgio Polvara - Gpx


Just to add to Gpx answer: you can keep your indentation with this library.

import {oneLineTrim} from 'common-tags'

oneLineTrim`
  https://news.com/article
  ?utm_source=designernews.com
`)
// https://news.com/article?utm_source=designernews.com
like image 3
hhh Avatar answered Sep 23 '22 21:09

hhh