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?
To escape a backtick in a template literal, put a backslash ( \ ) before the backtick.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With