Languages
[Edit]
EN

TypeScript - multiline string

9 points
Created by:
Mariam-Barron
811

In this article, we're going to have a look at how to create a multiline string in TypeScript.

As multiline string, we mean string that was divided into multiple lines only to be more readable by programmers.

Quick solution:

Since ES6 you can use tempalte literals, so use ` character instead of ' or " characters.

The character (grave accent) is located togather with Tilde key on the QWERTY keyboard.

Grave accent location on QWERTY keyboard.
Grave accent location on QWERTY keyboard.

1. Template literals (template strings) example

Edit

This approach was introduced in ECMAScript 2015 (ES6) that is supported by TypeScript.

The main disadvantage of this approach is necessary to remove white space prefixes for each line if we want to format string as we use it in the source code.

Output:

 

2. + operator with strings example

Edit

This approach solves the problem of white character prefixes for formatted source code but introduces some complications about taking cate of " and + characters.

Output:

 

3. Backslash at the end of each line example

Edit

This approach is very similar to template literals and introduces problems with taking care of \ character at end of the lines.

Note: this feature is not part of ECMAScript standard, so when source code is transpiled we should be sure it is transpiled to safe code too.

Output:

 

4. Array join method example

Edit

This approach is more like a cheat but gives a multiline string effect.

Output:

 

References

Edit
  1. Template literals - MDN
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join