Languages
[Edit]
EN

TypeScript - multiline string

9 points
Created by:
Kate_C
2854

In this article, we're going to have a look at how to create multiline string in TypeScript. As multiline string we mean string that was divided into multiple lines only do me more readable by programmers.

There are few ways how to do it:

  • template literals - introduced in ECMAScript 2015 (ES6),
  • + operator with strings, 
  • backslash at the end of each line - this approach is not part of standard.

1. Template literals (template strings) example

This approach was introduced in ES6 that is supported by TypeScript.

Main disadvantage of this approach are white space prefixes for each line if we want to format code clearly.

let text = `Line 1;
Line 2;
Line 3;
Line 4;
Line 5;`;

console.log(text);

Output:

Line 1;
Line 2;
Line 3;
Line 4;
Line 5;

2. + operator with strings example

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

let text = 'Line 1;' +
    'Line 2;' +
    'Line 3;' +
    'Line 4;' +
    'Line 5;';

console.log(text);

Output:

Line 1;Line 2;Line 3;Line 4;Line 5;

3. Backslash at the end of each line example

This approach is very similar to template literals and introduces problem with taking care of \ character at end of 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.

let text = 'Line 1;\
Line 2;\
Line 3;\
Line 4;\
Line 5;';

console.log(text);

Output:

Line 1;Line 2;Line 3;Line 4;Line 5;

4. Array.join method example

This approach is more like cheat to achieve multiline string effect.

let array: Array<string> = [
    'This',
    'is',
    'multiline',
    'text.'
];

console.log(array.join('\n'));

Output:

This
is
multiline
text.

References

  1. Template literals - MDN
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.