How to Create Multiline Strings in TypeScript?

When I first started working with TypeScript, I often found myself needing to handle multiline strings, whether for logging messages, writing HTML templates, or other purposes.

In this tutorial, I will explain how to create multiline strings in TypeScript. By the end of the tutorial, you’ll have a solid understanding of how to work with multiline strings in TypeScript.

Multiline Strings in TypeScript

Multiline strings are strings that span across multiple lines of code. They are particularly useful when you need to include long text blocks, such as HTML templates, SQL queries, or even JSON data. In TypeScript, there are several ways to create multiline strings.

Now let me show you these methods with examples.

1. Using Template Literals

Template literals, introduced in ES6, provide a straightforward way to create multiline strings in TypeScript. They are enclosed by backticks (`) instead of single or double quotes. One of the significant benefits of template literals is that they preserve the formatting, including line breaks and indentation.

Example

Here is an example of creating a multiline string in TypeScript using template literals.

const address = `123 Main Street
Springfield, IL
USA`;

console.log(address);

In this example, the address variable contains a multiline string that includes line breaks.

I executed the above TypeScript code, and you can see the exact output in the screenshot below:

Create Multiline Strings in TypeScript

Check out Remove Spaces from a String in TypeScript

2. String Concatenation

Before template literals were introduced, developers often used string concatenation to create multiline strings in TypeScript. This method involves using the + operator to concatenate multiple strings.

Let me show you an example to help you understand better.

Example

const address = "123 Main Street\n" +
                "Springfield, IL\n" +
                "USA";

console.log(address);

While string concatenation works, it can become cumbersome and hard to read, especially for longer strings. It also requires explicit newline characters (\n) to indicate line breaks.

You can see the exact output in the screenshot below:

how to write multiline string in typescript

Check out Convert a Number to a String in TypeScript

3. Using Array and Join() Method

Another approach to creating multiline strings is using an array of strings and the join() method. This method is particularly useful when dealing with dynamic content.

Example

const addressParts = [
  "123 Main Street",
  "Springfield, IL",
  "USA"
];

const address = addressParts.join("\n");
console.log(address);

This method allows you to manage each line as a separate element in an array, which can be helpful when you need to manipulate individual lines before joining them into a single string.

Check out Replace All Occurrences of a Substring in a String in TypeScript

4. Newline Escaping

If you prefer to stick with single or double quotes, you can use newline escaping to create multiline strings in TypeScript. This involves using the backslash (\) character at the end of each line to indicate that the string continues on the next line.

Example

const address = "123 Main Street\n\
Springfield, IL\n\
USA";

console.log(address);

While this method is compatible with older JavaScript versions, it can make your code harder to read and maintain compared to template literals.

You can see the exact output in the screenshot below:

create multi line string in TypeScript

Check out Check if a String is Empty in TypeScript

Practical Applications of Creating Multiline Strings in TypeScript

Let me show you two practical examples of creating multiple strings in TypeScript.

HTML Templates

When building web applications, you often need to include HTML templates within your TypeScript code. Multiline strings make it easy to embed HTML without losing readability.

Example

const htmlTemplate = `
  <div>
    <h1>Welcome to Springfield</h1>
    <p>123 Main Street, Springfield, IL, USA</p>
  </div>
`;

document.body.innerHTML = htmlTemplate;

SQL Queries

When working with databases, you might need to write complex SQL queries that span multiple lines. Multiline strings help you maintain the structure of your queries.

Example

const query = `
  SELECT *
  FROM users
  WHERE city = 'Springfield'
  AND state = 'IL';
`;

console.log(query);

JSON Data

If you need to include JSON data within your code, multiline strings can help you maintain the formatting and readability of the JSON structure.

Example

const jsonData = `
  {
    "name": "John Doe",
    "address": {
      "street": "123 Main Street",
      "city": "Springfield",
      "state": "IL",
      "country": "USA"
    }
  }
`;

console.log(jsonData);

Check out Split a String by Comma in TypeScript

Best Practices for Multiline Strings in TypeScript

Let me show you some best practices that you should follow while creating multiline strings in TypeScript.

Use Template Literals Whenever Possible

Template literals are the most modern and readable way to create multiline strings. They preserve formatting and make your code easier to understand.

Avoid Excessive Line Lengths

Even with multiline strings, try to avoid excessively long lines. Break your strings into manageable chunks to enhance readability.

Keep Indentation Consistent

When using template literals, maintain consistent indentation to ensure your code remains clean and easy to follow.

Use Comments for Clarity

If your multiline strings contain complex content, consider adding comments to explain their purpose and structure.

Conclusion

In this tutorial, I have explained how to create multiline strings in TypeScript using various methods, such as template literals, string concatenation, arrays, and newline escaping.

Whether you’re working with HTML templates, SQL queries, or JSON data, you should understand how to handle multiline strings in TypeScript.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.